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
+5378 -5031

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
+86 -79
View File
@@ -1,12 +1,13 @@
plugins {
id 'java'
id 'java-library'
id 'maven'
id 'maven-publish'
id 'com.github.johnrengelman.shadow' version '6.0.0'
id 'net.minecrell.plugin-yml.bukkit' version '0.3.0'
id 'com.palantir.git-version' version '0.12.3'
id 'org.checkerframework' version '0.5.9'
id 'checkstyle'
id 'java'
id 'java-library'
id 'maven'
id 'maven-publish'
id 'com.github.johnrengelman.shadow' version '6.0.0'
id 'net.minecrell.plugin-yml.bukkit' version '0.3.0'
id 'com.palantir.git-version' version '0.12.3'
id 'org.checkerframework' version '0.5.9'
}
// Gets the git commit hash of the latest commit, used for version string
@@ -17,90 +18,96 @@ group = 'net.draycia'
description = 'CarbonChat'
version = project.property('projectVersion') + '-' + gitHash
repositories {
mavenLocal()
mavenCentral()
checkstyle {
def configRoot = new File(rootProject.projectDir, '.checkstyle')
toolVersion = '8.34'
configDirectory = configRoot
configProperties = [basedir: configRoot.getAbsolutePath()]
}
maven {url = 'https://maven.enginehub.org/repo/'}
maven {url = 'https://repo.maven.apache.org/maven2'}
maven {url = 'https://papermc.io/repo/repository/maven-public/'}
maven {url = 'https://oss.sonatype.org/content/groups/public/'}
maven {url = 'https://repo.extendedclip.com/content/repositories/placeholderapi/'}
maven {url = 'https://jitpack.io'}
maven {url = 'https://dl.bintray.com/ichbinjoe/public/'}
maven {url = 'https://repo.codemc.org/repository/maven-public/'}
maven {url = 'https://repo.minebench.de/'}
maven {url = "https://repo.aikar.co/content/groups/aikar/"}
maven {url = 'https://raw.githubusercontent.com/JorelAli/CommandAPI/mvn-repo/'}
repositories {
mavenLocal()
mavenCentral()
maven { url = 'https://maven.enginehub.org/repo/' }
maven { url = 'https://repo.maven.apache.org/maven2' }
maven { url = 'https://papermc.io/repo/repository/maven-public/' }
maven { url = 'https://oss.sonatype.org/content/groups/public/' }
maven { url = 'https://repo.extendedclip.com/content/repositories/placeholderapi/' }
maven { url = 'https://jitpack.io' }
maven { url = 'https://dl.bintray.com/ichbinjoe/public/' }
maven { url = 'https://repo.codemc.org/repository/maven-public/' }
maven { url = 'https://repo.minebench.de/' }
maven { url = "https://repo.aikar.co/content/groups/aikar/" }
maven { url = 'https://raw.githubusercontent.com/JorelAli/CommandAPI/mvn-repo/' }
}
dependencies {
// Components
compile 'net.kyori:adventure-api:4.0.0-SNAPSHOT'
compile 'net.kyori:adventure-nbt:4.0.0-SNAPSHOT'
compile 'net.kyori:adventure-platform-bukkit:4.0.0-SNAPSHOT'
compile 'net.kyori:adventure-text-minimessage:3.0.0-SNAPSHOT'
compile 'de.themoep:minedown-adventure:1.6.1-SNAPSHOT'
checkstyle("ca.stellardrift:stylecheck:0.1-SNAPSHOT")
// Databases
compile 'co.aikar:idb-bukkit:1.0.0-SNAPSHOT'
compile 'com.zaxxer:HikariCP:2.4.1'
// Components
compile 'net.kyori:adventure-api:4.0.0-SNAPSHOT'
compile 'net.kyori:adventure-nbt:4.0.0-SNAPSHOT'
compile 'net.kyori:adventure-platform-bukkit:4.0.0-SNAPSHOT'
compile 'net.kyori:adventure-text-minimessage:3.0.0-SNAPSHOT'
compile 'de.themoep:minedown-adventure:1.6.1-SNAPSHOT'
// Messaging
compile 'io.github.leonardosnt:bungeechannelapi:1.0.0-SNAPSHOT'
compile 'io.lettuce:lettuce-core:6.0.0.M1'
// Databases
compile 'co.aikar:idb-bukkit:1.0.0-SNAPSHOT'
compile 'com.zaxxer:HikariCP:2.4.1'
// Commands
compile "dev.jorel:commandapi-shade:4.1"
// Messaging
compile 'io.github.leonardosnt:bungeechannelapi:1.0.0-SNAPSHOT'
compile 'io.lettuce:lettuce-core:6.0.0.M1'
// Plugins
compileOnly('com.gmail.nossr50.mcMMO:mcMMO:2.1.143') {
exclude group: 'org.jetbrains', module: 'annotations'
}
compileOnly 'com.github.TownyAdvanced:Towny:0.96.2.0'
compileOnly('com.sk89q.worldguard:worldguard-bukkit:7.0.4-SNAPSHOT') {
exclude group: 'org.spigotmc', module: 'spigot-api' // Honestly?
}
compileOnly 'me.clip:placeholderapi:2.10.9'
compileOnly 'com.github.TownyAdvanced:Towny:0.96.1.11'
compileOnly 'com.github.MilkBowl:VaultAPI:1.7'
compileOnly 'com.vexsoftware:nuvotifier-universal:2.6.0'
compileOnly 'net.luckperms:api:5.1'
// Commands
compile "dev.jorel:commandapi-shade:4.1"
// Server
compileOnly 'com.destroystokyo.paper:paper-api:1.16.2-R0.1-SNAPSHOT'
// Plugins
compileOnly('com.gmail.nossr50.mcMMO:mcMMO:2.1.143') {
exclude group: 'org.jetbrains', module: 'annotations'
}
compileOnly 'com.github.TownyAdvanced:Towny:0.96.2.0'
compileOnly('com.sk89q.worldguard:worldguard-bukkit:7.0.4-SNAPSHOT') {
exclude group: 'org.spigotmc', module: 'spigot-api' // Honestly?
}
compileOnly 'me.clip:placeholderapi:2.10.9'
compileOnly 'com.github.TownyAdvanced:Towny:0.96.1.11'
compileOnly 'com.github.MilkBowl:VaultAPI:1.7'
compileOnly 'com.vexsoftware:nuvotifier-universal:2.6.0'
compileOnly 'net.luckperms:api:5.1'
// Server
compileOnly 'com.destroystokyo.paper:paper-api:1.16.2-R0.1-SNAPSHOT'
}
// Generates plugin.yml automatically
bukkit {
name = project.description
version = project.version
main = 'net.draycia.carbon.CarbonChat'
apiVersion = '1.13'
author = 'Draycia'
depend = ['PlaceholderAPI', 'Vault']
softDepend = ['LuckPerms', 'Towny', 'mcMMO', 'WorldGuard']
loadBefore = ["Essentials"]
permissions {
'carbonchat.channels.global.see' {
setDefault("TRUE")
}
'carbonchat.channels.global.use' {
setDefault("TRUE")
}
name = project.description
version = project.version
main = 'net.draycia.carbon.CarbonChat'
apiVersion = '1.13'
author = 'Draycia'
depend = ['PlaceholderAPI', 'Vault']
softDepend = ['LuckPerms', 'Towny', 'mcMMO', 'WorldGuard']
loadBefore = ["Essentials"]
permissions {
'carbonchat.channels.global.see' {
setDefault("TRUE")
}
'carbonchat.channels.global.use' {
setDefault("TRUE")
}
}
}
sourceCompatibility = '1.8'
// Set output directory and encoding
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
tasks.withType(Jar) {
getDestinationDirectory().set(file("$rootDir/build"))
options.encoding = 'UTF-8'
options.compilerArgs += ['-Xlint:all']
}
// Automatically shadowJar when building
@@ -108,25 +115,25 @@ tasks.build.dependsOn tasks.shadowJar
// Output a single jar
shadowJar {
minimize()
archiveFileName.set(project.description + "-" + project.property('projectVersion') + ".jar")
minimize()
archiveFileName.set(project.description + "-" + project.property('projectVersion') + ".jar")
}
jar {
archiveFileName.set(project.description + "-" + project.property('projectVersion') + ".jar")
archiveFileName.set(project.description + "-" + project.property('projectVersion') + ".jar")
}
// Automatically relocate all shaded dependencies
import com.github.jengelman.gradle.plugins.shadow.tasks.ConfigureShadowRelocation
task relocateShadowJar(type: ConfigureShadowRelocation) {
target = tasks.shadowJar
prefix = "net.draycia.carbon.libs" // Default value is "shadow"
target = tasks.shadowJar
prefix = "net.draycia.carbon.libs" // Default value is "shadow"
}
tasks.shadowJar.dependsOn tasks.relocateShadowJar
// Cleanup custom output directory on clean task
clean.doFirst {
delete "$rootDir/build/bundled"
}
delete "$rootDir/build/bundled"
}
+214 -194
View File
@@ -1,8 +1,27 @@
package net.draycia.carbon;
import dev.jorel.commandapi.CommandAPI;
import net.draycia.carbon.channels.contexts.impl.*;
import net.draycia.carbon.listeners.*;
import net.draycia.carbon.channels.contexts.impl.DistanceContext;
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.ChannelManager;
import net.draycia.carbon.managers.CommandManager;
@@ -28,236 +47,237 @@ import java.lang.reflect.Field;
public final class CarbonChat extends JavaPlugin {
private static final int BSTATS_PLUGIN_ID = 8720;
private static final int BSTATS_PLUGIN_ID = 8720;
private Permission permission;
private Permission permission;
private CommandManager commandManager;
private ChannelManager channelManager;
private AdventureManager adventureManager;
private ContextManager contextManager;
private CommandManager commandManager;
private ChannelManager channelManager;
private AdventureManager adventureManager;
private ContextManager contextManager;
private UserService userService;
private MessageManager messageManager;
private UserService userService;
private MessageManager messageManager;
private YamlConfiguration modConfig;
private YamlConfiguration languageConfig;
private YamlConfiguration commandsConfig;
private YamlConfiguration modConfig;
private YamlConfiguration languageConfig;
private YamlConfiguration commandsConfig;
private FilterHandler filterHandler;
private FilterHandler filterHandler;
public static final LegacyComponentSerializer LEGACY =
LegacyComponentSerializer.builder()
.extractUrls()
.hexColors()
.character('§')
.useUnusualXRepeatedCharacterHexFormat()
.build();
public static final LegacyComponentSerializer LEGACY =
LegacyComponentSerializer.builder()
.extractUrls()
.hexColors()
.character('§')
.useUnusualXRepeatedCharacterHexFormat()
.build();
@Override
public void onLoad() {
CommandAPI.onLoad(false);
@Override
public void onLoad() {
CommandAPI.onLoad(false);
}
@Override
public void onEnable() {
this.checkForBungee();
CommandAPI.onEnable(this);
final Metrics metrics = new Metrics(this, BSTATS_PLUGIN_ID);
// Ensure config is present to be modified by the user
if (!(new File(this.getDataFolder(), "config.yml").exists())) {
this.saveDefaultConfig();
}
@Override
public void onEnable() {
checkForBungee();
CommandAPI.onEnable(this);
Metrics metrics = new Metrics(this, BSTATS_PLUGIN_ID);
// Ensure config is present to be modified by the user
if (!(new File(getDataFolder(), "config.yml").exists())) {
saveDefaultConfig();
}
if (!(new File(getDataFolder(), "moderation.yml").exists())) {
saveResource("moderation.yml", false);
}
if (!(new File(getDataFolder(), "language.yml").exists())) {
saveResource("language.yml", false);
}
if (!(new File(getDataFolder(), "commands.yml").exists())) {
saveResource("commands.yml", false);
}
loadModConfig();
loadLanguage();
// Setup Adventure
adventureManager = new AdventureManager(this);
// Setup vault and permissions
permission = getServer().getServicesManager().getRegistration(Permission.class).getProvider();
// Initialize managers
channelManager = new ChannelManager(this);
contextManager = new ContextManager();
messageManager = new MessageManager(this);
commandManager = new CommandManager(this);
String storageType = getConfig().getString("storage.type");
if (storageType.equalsIgnoreCase("mysql")) {
getLogger().info("Enabling MySQL storage!");
userService = new MySQLUserService(this);
} else if (storageType.equalsIgnoreCase("json")) {
getLogger().info("Enabling JSON storage!");
userService = new JSONUserService(this);
} else {
getLogger().warning("Invalid storage type selected! Falling back to JSON.");
userService = new JSONUserService(this);
}
// Setup listeners
setupListeners();
registerContexts();
new CarbonPlaceholders(this).register();
if (Bukkit.getPluginManager().isPluginEnabled("Towny")) {
getServer().getPluginManager().registerEvents(new TownyContext(this), this);
}
if (Bukkit.getPluginManager().isPluginEnabled("mcMMO")) {
getServer().getPluginManager().registerEvents(new mcMMOContext(this), this);
}
if (Bukkit.getPluginManager().isPluginEnabled("WorldGuard")) {
getServer().getPluginManager().registerEvents(new WorldGuardContext(this), this);
}
if (Bukkit.getServicesManager().isProvidedFor(Economy.class)) {
Bukkit.getPluginManager().registerEvents(new EconomyContext(this), this);
}
if (!FunctionalityConstants.HAS_HOVER_EVENT_METHOD) {
getLogger().warning("Item linking disabled! Please use Paper 1.16.2 #172 or newer.");
}
if (!(new File(this.getDataFolder(), "moderation.yml").exists())) {
this.saveResource("moderation.yml", false);
}
@Override
public void onDisable() {
userService.onDisable();
if (!(new File(this.getDataFolder(), "language.yml").exists())) {
this.saveResource("language.yml", false);
}
private void setupListeners() {
PluginManager pluginManager = getServer().getPluginManager();
filterHandler = new FilterHandler(this);
// Register chat listeners
pluginManager.registerEvents(new BukkitChatListener(this), this);
pluginManager.registerEvents(new CapsHandler(this), this);
pluginManager.registerEvents(new CustomPlaceholderHandler(this), this);
pluginManager.registerEvents(filterHandler, this);
pluginManager.registerEvents(new IgnoredPlayerHandler(), this);
pluginManager.registerEvents(new ItemLinkHandler(), this);
pluginManager.registerEvents(new LegacyFormatHandler(), this);
pluginManager.registerEvents(new MuteHandler(), this);
pluginManager.registerEvents(new OfflineNameHandler(), this);
pluginManager.registerEvents(new PingHandler(this), this);
pluginManager.registerEvents(new PlaceholderHandler(), this);
pluginManager.registerEvents(new PlayerJoinListener(this), this);
pluginManager.registerEvents(new RelationalPlaceholderHandler(), this);
pluginManager.registerEvents(new ShadowMuteHandler(this), this);
pluginManager.registerEvents(new UserFormattingHandler(), this);
pluginManager.registerEvents(new WhisperPingHandler(this), this);
if (!(new File(this.getDataFolder(), "commands.yml").exists())) {
this.saveResource("commands.yml", false);
}
@Override
public void reloadConfig() {
super.reloadConfig();
this.loadModConfig();
this.loadLanguage();
loadModConfig();
loadLanguage();
loadCommandsConfig();
// Setup Adventure
this.adventureManager = new AdventureManager(this);
// Setup vault and permissions
this.permission = this.getServer().getServicesManager().getRegistration(Permission.class).getProvider();
// Initialize managers
this.channelManager = new ChannelManager(this);
this.contextManager = new ContextManager();
this.messageManager = new MessageManager(this);
this.commandManager = new CommandManager(this);
final String storageType = this.getConfig().getString("storage.type");
if (storageType.equalsIgnoreCase("mysql")) {
this.getLogger().info("Enabling MySQL storage!");
this.userService = new MySQLUserService(this);
} else if (storageType.equalsIgnoreCase("json")) {
this.getLogger().info("Enabling JSON storage!");
this.userService = new JSONUserService(this);
} else {
this.getLogger().warning("Invalid storage type selected! Falling back to JSON.");
this.userService = new JSONUserService(this);
}
public void reloadFilters() {
filterHandler.reloadFilters();
// Setup listeners
this.setupListeners();
this.registerContexts();
new CarbonPlaceholders(this).register();
if (Bukkit.getPluginManager().isPluginEnabled("Towny")) {
this.getServer().getPluginManager().registerEvents(new TownyContext(this), this);
}
private boolean bungeeEnabled = false;
private void checkForBungee() {
try {
Class<?> spigotConfig = Class.forName("org.spigotmc.Spigotconfig");
Field bungee = spigotConfig.getField("bungee");
bungeeEnabled = bungee.getBoolean(null);
} catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException ignored) { }
if (Bukkit.getPluginManager().isPluginEnabled("mcMMO")) {
this.getServer().getPluginManager().registerEvents(new mcMMOContext(this), this);
}
public boolean isBungeeEnabled() {
return bungeeEnabled;
if (Bukkit.getPluginManager().isPluginEnabled("WorldGuard")) {
this.getServer().getPluginManager().registerEvents(new WorldGuardContext(this), this);
}
private void loadModConfig() {
modConfig = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "moderation.yml"));
if (Bukkit.getServicesManager().isProvidedFor(Economy.class)) {
Bukkit.getPluginManager().registerEvents(new EconomyContext(this), this);
}
private void loadLanguage() {
languageConfig = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "language.yml"));
if (!FunctionalityConstants.HAS_HOVER_EVENT_METHOD) {
this.getLogger().warning("Item linking disabled! Please use Paper 1.16.2 #172 or newer.");
}
}
private void loadCommandsConfig() {
commandsConfig = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "commands.yml"));
}
@Override
public void onDisable() {
this.userService.onDisable();
}
private void registerContexts() {
getContextManager().register("distance", new DistanceContext());
}
private void setupListeners() {
final PluginManager pluginManager = this.getServer().getPluginManager();
@NonNull
public YamlConfiguration getModConfig() {
return modConfig;
}
this.filterHandler = new FilterHandler(this);
@NonNull
public YamlConfiguration getCommandsConfig() {
return commandsConfig;
}
// Register chat listeners
pluginManager.registerEvents(new BukkitChatListener(this), this);
pluginManager.registerEvents(new CapsHandler(this), this);
pluginManager.registerEvents(new CustomPlaceholderHandler(this), this);
pluginManager.registerEvents(this.filterHandler, this);
pluginManager.registerEvents(new IgnoredPlayerHandler(), this);
pluginManager.registerEvents(new ItemLinkHandler(), this);
pluginManager.registerEvents(new LegacyFormatHandler(), this);
pluginManager.registerEvents(new MuteHandler(), this);
pluginManager.registerEvents(new OfflineNameHandler(), this);
pluginManager.registerEvents(new PingHandler(this), this);
pluginManager.registerEvents(new PlaceholderHandler(), this);
pluginManager.registerEvents(new PlayerJoinListener(this), this);
pluginManager.registerEvents(new RelationalPlaceholderHandler(), this);
pluginManager.registerEvents(new ShadowMuteHandler(this), this);
pluginManager.registerEvents(new UserFormattingHandler(), this);
pluginManager.registerEvents(new WhisperPingHandler(this), this);
@NonNull
public YamlConfiguration getLanguage() {
return languageConfig;
}
}
@NonNull
public Permission getPermission() {
return permission;
}
@Override
public void reloadConfig() {
super.reloadConfig();
@NonNull
public CommandManager getCommandManager() {
return commandManager;
}
this.loadModConfig();
this.loadLanguage();
this.loadCommandsConfig();
}
@NonNull
public ChannelManager getChannelManager() {
return channelManager;
}
public void reloadFilters() {
this.filterHandler.reloadFilters();
}
@NonNull
public MessageManager getMessageManager() {
return messageManager;
}
private boolean bungeeEnabled = false;
@NonNull
public UserService getUserService() {
return userService;
private void checkForBungee() {
try {
final Class<?> spigotConfig = Class.forName("org.spigotmc.Spigotconfig");
final Field bungee = spigotConfig.getField("bungee");
this.bungeeEnabled = bungee.getBoolean(null);
} catch (final ClassNotFoundException | NoSuchFieldException | IllegalAccessException ignored) {
}
}
@NonNull
public AdventureManager getAdventureManager() {
return adventureManager;
}
public boolean bungeeEnabled() {
return this.bungeeEnabled;
}
@NonNull
public ContextManager getContextManager() {
return contextManager;
}
private void loadModConfig() {
this.modConfig = YamlConfiguration.loadConfiguration(new File(this.getDataFolder(), "moderation.yml"));
}
private void loadLanguage() {
this.languageConfig = YamlConfiguration.loadConfiguration(new File(this.getDataFolder(), "language.yml"));
}
private void loadCommandsConfig() {
this.commandsConfig = YamlConfiguration.loadConfiguration(new File(this.getDataFolder(), "commands.yml"));
}
private void registerContexts() {
this.contextManager().register("distance", new DistanceContext());
}
@NonNull
public YamlConfiguration moderationConfig() {
return this.modConfig;
}
@NonNull
public YamlConfiguration commandsConfig() {
return this.commandsConfig;
}
@NonNull
public YamlConfiguration language() {
return this.languageConfig;
}
@NonNull
public Permission permission() {
return this.permission;
}
@NonNull
public CommandManager commandManager() {
return this.commandManager;
}
@NonNull
public ChannelManager channelManager() {
return this.channelManager;
}
@NonNull
public MessageManager messageManager() {
return this.messageManager;
}
@NonNull
public UserService userService() {
return this.userService;
}
@NonNull
public AdventureManager adventureManager() {
return this.adventureManager;
}
@NonNull
public ContextManager contextManager() {
return this.contextManager;
}
}
@@ -9,60 +9,64 @@ import org.bukkit.event.Listener;
import org.checkerframework.checker.nullness.qual.NonNull;
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> {
@NonNull
private final Map<@NonNull String, @NonNull ChatChannel> registry = new HashMap<>();
@NonNull
private final Map<@NonNull String, @NonNull ChatChannel> registry = new HashMap<>();
@NonNull
private final List<@NonNull AliasedChannelCommand> channelCommands = new ArrayList<>();
@NonNull
private final List<@NonNull AliasedChannelCommand> channelCommands = new ArrayList<>();
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public ChannelRegistry(@NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
public ChannelRegistry(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat;
}
@Override
public boolean register(@NonNull final String key, @NonNull final ChatChannel value) {
final boolean registerSuccessful = this.registry.putIfAbsent(key, value) == null;
if (registerSuccessful) {
final AliasedChannelCommand command = new AliasedChannelCommand(this.carbonChat, value);
this.channelCommands.add(command);
if (value instanceof Listener) {
Bukkit.getPluginManager().registerEvents((Listener) value, this.carbonChat);
}
}
@Override
public boolean register(@NonNull String key, @NonNull ChatChannel value) {
boolean registerSuccessful = registry.putIfAbsent(key, value) == null;
return registerSuccessful;
}
if (registerSuccessful) {
AliasedChannelCommand command = new AliasedChannelCommand(carbonChat, value);
@Override
@NonNull
public Collection<@NonNull ChatChannel> values() {
return this.registry.values();
}
channelCommands.add(command);
@Override
@Nullable
public ChatChannel channel(@NonNull final String key) {
return this.registry.get(key);
}
if (value instanceof Listener) {
Bukkit.getPluginManager().registerEvents((Listener) value, carbonChat);
}
}
@Override
public void clearAll() {
this.registry.clear();
return registerSuccessful;
}
@Override
@NonNull
public Collection<@NonNull ChatChannel> values() {
return registry.values();
}
@Override
@Nullable
public ChatChannel get(@NonNull String key) {
return registry.get(key);
}
@Override
public void clearAll() {
registry.clear();
for (AliasedChannelCommand command : channelCommands) {
carbonChat.getLogger().info("Unregistering command for channel: " + command.getChatChannel().getName());
CommandAPI.unregister(command.getCommandName());
}
for (final AliasedChannelCommand command : this.channelCommands) {
this.carbonChat.getLogger().info("Unregistering command for channel: " + command.chatChannel().name());
CommandAPI.unregister(command.commandName());
}
}
}
@@ -14,141 +14,139 @@ import java.util.regex.Pattern;
public abstract class ChatChannel implements ForwardingAudience {
/**
* @return The color that represents this channel. Optionally used in formatting.
*/
@Nullable
public abstract TextColor getChannelColor(@NonNull ChatUser user);
@NonNull
public abstract List<ChatUser> audiences();
/**
* @return The MiniMessage styled format for the group in this channel.
*/
@Nullable
public abstract String getFormat(@NonNull String group);
/**
* @return The color that represents this channel. Optionally used in formatting.
*/
@Nullable
public abstract TextColor channelColor(@NonNull ChatUser user);
/**
* @return If this is the default (typically Global) channel players use when they're in no other channel.
*/
public abstract boolean isDefault();
/**
* @return The MiniMessage styled format for the group in this channel.
*/
@Nullable
public abstract String format(@NonNull String group);
/**
* @return If this channel can be toggled off and if players can ignore player messages in this channel.
*/
public abstract boolean isIgnorable();
/**
* @return If this is the default (typically Global) channel players use when they're in no other channel.
*/
public abstract boolean isDefault();
/**
* @return If this channel should be synced cross server
* @deprecated Use {@link #isCrossServer()} instead
*/
@Deprecated
public abstract boolean shouldBungee();
/**
* @return If this channel can be toggled off and if players can ignore player messages in this channel.
*/
public abstract boolean ignorable();
/**
* @return If this channel should be synced cross server
*/
public abstract boolean isCrossServer();
/**
* @return If this channel should be synced cross server
* @deprecated Use {@link #crossServer()} instead
*/
@Deprecated
public abstract boolean bungee();
/**
* @return The name of this channel.
*/
@NonNull
public abstract String getName();
/**
* @return If this channel should be synced cross server
*/
public abstract boolean crossServer();
@NonNull
public abstract String getKey();
/**
* @return The name of this channel.
*/
@NonNull
public abstract String name();
@Nullable
public abstract String getMessagePrefix();
@NonNull
public abstract String key();
@Nullable
public abstract String getAliases();
@Nullable
public abstract String messagePrefix();
/**
* @return The message to be sent to the player when switching to this channel.
*/
@Nullable
public abstract String getSwitchMessage();
@Nullable
public abstract String aliases();
@Nullable
public abstract String getSwitchOtherMessage();
/**
* @return The message to be sent to the player when switching to this channel.
*/
@Nullable
public abstract String switchMessage();
@Nullable
public abstract String getSwitchFailureMessage();
@Nullable
public abstract String switchOtherMessage();
@Nullable
public abstract String getCannotIgnoreMessage();
@Nullable
public abstract String switchFailureMessage();
/**
* @return The message to be send to the player when toggling this channel off.
*/
@Nullable
public abstract String getToggleOffMessage();
@Nullable
public abstract String cannotIgnoreMessage();
/**
* @return The message to be send to the player when toggling this channel on.
*/
@Nullable
public abstract String getToggleOnMessage();
/**
* @return The message to be send to the player when toggling this channel off.
*/
@Nullable
public abstract String toggleOffMessage();
@Nullable
public abstract String getToggleOtherOnMessage();
/**
* @return The message to be send to the player when toggling this channel on.
*/
@Nullable
public abstract String toggleOnMessage();
@Nullable
public abstract String getToggleOtherOffMessage();
@Nullable
public abstract String toggleOtherOnMessage();
@Nullable
public abstract String getCannotUseMessage();
@Nullable
public abstract String toggleOtherOffMessage();
public abstract boolean primaryGroupOnly();
@Nullable
public abstract String cannotUseMessage();
public abstract boolean honorsRecipientList();
public abstract boolean primaryGroupOnly();
public abstract boolean permissionGroupMatching();
public abstract boolean honorsRecipientList();
public abstract boolean testContext(@NonNull ChatUser sender, @NonNull ChatUser target);
public abstract boolean permissionGroupMatching();
@Nullable
public abstract Object getContext(@NonNull String key);
public abstract boolean shouldCancelChatEvent();
@NonNull
public abstract List<@NonNull String> getGroupOverrides();
public abstract boolean testContext(@NonNull ChatUser sender, @NonNull ChatUser target);
/**
* @return If the player can use this channel.
*/
public abstract boolean canPlayerUse(@NonNull ChatUser user);
@NonNull
public abstract List<@NonNull Pattern> itemLinkPatterns();
public abstract boolean canPlayerSee(@NonNull ChatUser sender, @NonNull ChatUser target, boolean checkSpying);
@Nullable
public abstract Object context(@NonNull String key);
public abstract boolean canPlayerSee(@NonNull ChatUser target, boolean checkSpying);
@NonNull
public abstract List<@NonNull String> groupOverrides();
/**
* @return If the channel should forward its formatting / formatted message to other servers
*/
public boolean shouldForwardFormatting() {
return true;
}
/**
* @return If the player can use this channel.
*/
public abstract boolean canPlayerUse(@NonNull ChatUser user);
@NonNull
public abstract List<@NonNull Pattern> getItemLinkPatterns();
public abstract boolean canPlayerSee(@NonNull ChatUser sender, @NonNull ChatUser target, boolean checkSpying);
/**
* Parses the specified message, calls a {@link PreChatFormatEvent}, and sends the message to everyone who can view this channel.
*
* @param user The player who is saying the message.
* @param message The message to be sent.
*/
@NonNull
public abstract Component sendMessage(@NonNull ChatUser user, @NonNull String message, boolean fromBungee);
public abstract boolean canPlayerSee(@NonNull ChatUser target, boolean checkSpying);
@NonNull
public abstract Component sendMessage(@NonNull ChatUser user, @NonNull Collection<@NonNull ChatUser> recipients, @NonNull String message, boolean fromBungee);
/**
* Parses the specified message, calls a {@link PreChatFormatEvent}, and sends the message to everyone who can view this channel.
*
* @param user The player who is saying the message.
* @param message The message to be sent.
*/
@NonNull
public abstract Component sendMessage(@NonNull ChatUser user, @NonNull String message, boolean fromBungee);
public abstract void sendComponent(@NonNull ChatUser user, @NonNull Component component);
@NonNull
public abstract Component sendMessage(@NonNull ChatUser user, @NonNull Collection<@NonNull ChatUser> recipients, @NonNull String message, boolean fromBungee);
@Nullable
public String processPlaceholders(@NonNull ChatUser user, @Nullable String input) { return input; }
public abstract void sendComponent(@NonNull ChatUser user, @NonNull Component component);
public abstract boolean shouldCancelChatEvent();
@Nullable
public String processPlaceholders(@NonNull final ChatUser user, @Nullable final String input) {
return input;
}
}
@@ -6,46 +6,46 @@ import org.checkerframework.checker.nullness.qual.NonNull;
public interface MessageContext {
@NonNull
ChatUser getSender();
@NonNull
ChatUser sender();
@NonNull
ChatUser getTarget();
@NonNull
ChatUser target();
ChatChannel getChatChannel();
ChatChannel chatChannel();
Object getValue();
Object value();
default boolean isDouble() {
return getValue() instanceof Double;
}
default boolean isDouble() {
return this.value() instanceof Double;
}
default boolean isString() {
return getValue() instanceof String;
}
default boolean isString() {
return this.value() instanceof String;
}
default boolean isInteger() {
return getValue() instanceof Integer;
}
default boolean isInteger() {
return this.value() instanceof Integer;
}
default boolean isBoolean() {
return getValue() instanceof Boolean;
}
default boolean isBoolean() {
return this.value() instanceof Boolean;
}
default Double asDouble() {
return (Double)getValue();
}
default Double asDouble() {
return (Double) this.value();
}
default String asString() {
return (String)getValue();
}
default String asString() {
return (String) this.value();
}
default Integer asInteger() {
return (Integer)getValue();
}
default Integer asInteger() {
return (Integer) this.value();
}
default Boolean asBoolean() {
return (Boolean)getValue();
}
default Boolean asBoolean() {
return (Boolean) this.value();
}
}
@@ -8,33 +8,33 @@ import java.util.function.Function;
public class DistanceContext implements Function<MessageContext, Boolean> {
@Override
@NonNull
public Boolean apply(@NonNull MessageContext context) {
if (!context.getSender().isOnline() || !context.getTarget().isOnline()) {
return false;
}
if (context.isBoolean() && !context.asBoolean()) {
return true;
}
Location senderLocation = context.getSender().asPlayer().getLocation();
Location targetLocation = context.getTarget().asPlayer().getLocation();
if (!senderLocation.getWorld().equals(targetLocation.getWorld())) {
return false;
}
if (context.isDouble()) {
Double value = context.asDouble();
if (value > 0) {
return senderLocation.distance(targetLocation) <= value;
}
}
return true;
@Override
@NonNull
public Boolean apply(@NonNull final MessageContext context) {
if (!context.sender().online() || !context.target().online()) {
return false;
}
if (context.isBoolean() && !context.asBoolean()) {
return true;
}
final Location senderLocation = context.sender().player().getLocation();
final Location targetLocation = context.target().player().getLocation();
if (!senderLocation.getWorld().equals(targetLocation.getWorld())) {
return false;
}
if (context.isDouble()) {
final Double value = context.asDouble();
if (value > 0) {
return senderLocation.distance(targetLocation) <= value;
}
}
return true;
}
}
@@ -9,75 +9,75 @@ import org.bukkit.event.Listener;
import org.checkerframework.checker.nullness.qual.NonNull;
public class EconomyContext implements Listener {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final Economy economy;
@NonNull
private final Economy economy;
public EconomyContext(@NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
this.economy = carbonChat.getServer().getServicesManager().getRegistration(Economy.class).getProvider();
public EconomyContext(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat;
this.economy = this.carbonChat.getServer().getServicesManager().getRegistration(Economy.class).getProvider();
}
@EventHandler
public void onChatReqBal(final PreChatFormatEvent event) {
final Object requiredBalObject = event.channel().context("vault-balance");
final Double requiredBal;
if (requiredBalObject instanceof Double) {
requiredBal = (Double) requiredBalObject;
} else if (requiredBalObject instanceof Integer) {
requiredBal = Double.valueOf((Integer) requiredBalObject);
} else {
return;
}
@EventHandler
public void onChatReqBal(PreChatFormatEvent event) {
Object requiredBalObject = event.getChannel().getContext("vault-balance");
Double requiredBal;
if (requiredBalObject instanceof Double) {
requiredBal = (Double) requiredBalObject;
} else if (requiredBalObject instanceof Integer) {
requiredBal = Double.valueOf((Integer) requiredBalObject);
} else {
return;
}
if (requiredBal.equals(0.0)) {
return;
}
Player player = event.getUser().asPlayer();
if (!economy.has(player, requiredBal)) {
event.setCancelled(true);
event.getUser().sendMessage(carbonChat.getAdventureManager()
.processMessageWithPapi(player, event.getChannel().getCannotUseMessage()));
}
if (requiredBal.equals(0.0)) {
return;
}
@EventHandler
public void onChatCost(PreChatFormatEvent event) {
Object costObject = event.getChannel().getContext("vault-cost");
final Player player = event.user().player();
Double cost;
if (!this.economy.has(player, requiredBal)) {
event.setCancelled(true);
if (costObject instanceof Double) {
cost = (Double) costObject;
} else if (costObject instanceof Integer) {
cost = Double.valueOf((Integer) costObject);
} else {
return;
}
if (cost.equals(0.0)) {
return;
}
Player player = event.getUser().asPlayer();
if (!economy.has(player, cost)) {
event.setCancelled(true);
event.getUser().sendMessage(carbonChat.getAdventureManager()
.processMessageWithPapi(player, event.getChannel().getCannotUseMessage()));
return;
}
economy.withdrawPlayer(player, cost);
event.user().sendMessage(this.carbonChat.adventureManager()
.processMessageWithPapi(player, event.channel().cannotUseMessage()));
}
}
@EventHandler
public void onChatCost(final PreChatFormatEvent event) {
final Object costObject = event.channel().context("vault-cost");
final Double cost;
if (costObject instanceof Double) {
cost = (Double) costObject;
} else if (costObject instanceof Integer) {
cost = Double.valueOf((Integer) costObject);
} else {
return;
}
if (cost.equals(0.0)) {
return;
}
final Player player = event.user().player();
if (!this.economy.has(player, cost)) {
event.setCancelled(true);
event.user().sendMessage(this.carbonChat.adventureManager()
.processMessageWithPapi(player, event.channel().cannotUseMessage()));
return;
}
this.economy.withdrawPlayer(player, cost);
}
}
@@ -6,41 +6,44 @@ import net.draycia.carbon.storage.ChatUser;
import org.checkerframework.checker.nullness.qual.NonNull;
public class SimpleMessageContext implements MessageContext {
@NonNull
private final ChatUser sender;
@NonNull
private final ChatUser target;
@NonNull
private final ChatUser sender;
private final ChatChannel chatChannel;
private final Object value;
@NonNull
private final ChatUser target;
public SimpleMessageContext(@NonNull ChatUser sender, @NonNull ChatUser target, ChatChannel chatChannel, Object value) {
this.sender = sender;
this.target = target;
this.chatChannel = chatChannel;
this.value = value;
}
private final ChatChannel chatChannel;
private final Object value;
@Override
@NonNull
public ChatUser getSender() {
return sender;
}
public SimpleMessageContext(@NonNull final ChatUser sender, @NonNull final ChatUser target,
@NonNull final ChatChannel chatChannel, @NonNull final Object value) {
this.sender = sender;
this.target = target;
this.chatChannel = chatChannel;
this.value = value;
}
@Override
@NonNull
public ChatUser getTarget() {
return target;
}
@Override
@NonNull
public ChatUser sender() {
return this.sender;
}
@Override
public ChatChannel getChatChannel() {
return chatChannel;
}
@Override
@NonNull
public ChatUser target() {
return this.target;
}
@Override
public Object getValue() {
return value;
}
@Override
public ChatChannel chatChannel() {
return this.chatChannel;
}
@Override
public Object value() {
return this.value;
}
}
@@ -15,95 +15,95 @@ import org.checkerframework.checker.nullness.qual.NonNull;
public final class TownyContext implements Listener {
@NonNull
private static final String KEY = "towny-town";
@NonNull
private static final String KEY = "towny-town";
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public TownyContext(@NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
public TownyContext(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat;
this.carbonChat.getContextManager().register(KEY, (context) -> {
if ((context.getValue() instanceof Boolean) && ((Boolean) context.getValue())) {
return isInSameTown(context.getSender(), context.getTarget());
}
this.carbonChat.contextManager().register(KEY, context -> {
if ((context.value() instanceof Boolean) && ((Boolean) context.value())) {
return this.isInSameTown(context.sender(), context.target());
}
return true;
});
return true;
});
}
@EventHandler(ignoreCancelled = true)
public void onChannelSwitch(final ChannelSwitchEvent event) {
final Object town = event.channel().context(KEY);
if ((town instanceof Boolean) && ((Boolean) town)) {
if (!this.isInTown(event.user())) {
event.setCancelled(true);
event.failureMessage(this.carbonChat.getConfig().getString("contexts.Towny.cancellation-message"));
}
}
}
@EventHandler(ignoreCancelled = true)
public void onChannelMessage(final PreChatFormatEvent event) {
// TODO: event.setFailureMessage
final Object town = event.channel().context(KEY);
if ((town instanceof Boolean) && ((Boolean) town)) {
if (!this.isInTown(event.user())) {
event.setCancelled(true);
}
}
}
@EventHandler
public void onResidentRemove(final TownRemoveResidentEvent event) {
final String name = event.getResident().getName();
final ChatUser user = this.carbonChat.userService().wrap(name);
final Object town = user.selectedChannel().context(KEY);
if ((town instanceof Boolean) && ((Boolean) town)) {
user.clearSelectedChannel();
}
}
@EventHandler
public void onPlayerJoin(final PlayerJoinEvent event) {
final ChatUser user = this.carbonChat.userService().wrap(event.getPlayer());
final Object town = user.selectedChannel().context(KEY);
if ((town instanceof Boolean) && ((Boolean) town) && !this.isInTown(user)) {
user.clearSelectedChannel();
}
}
public boolean isInTown(@NonNull final ChatUser user) {
try {
return TownyAPI.getInstance().getDataSource().getResident(user.player().getName()).hasTown();
} catch (final NotRegisteredException exception) {
exception.printStackTrace();
}
@EventHandler(ignoreCancelled = true)
public void onChannelSwitch(ChannelSwitchEvent event) {
Object town = event.getChannel().getContext(KEY);
return false;
}
if ((town instanceof Boolean) && ((Boolean) town)) {
if (!isInTown(event.getUser())) {
event.setCancelled(true);
event.setFailureMessage(carbonChat.getConfig().getString("contexts.Towny.cancellation-message"));
}
}
public boolean isInSameTown(@NonNull final ChatUser user1, @NonNull final ChatUser user2) {
if (!user1.online() || !user2.online()) {
return false;
}
@EventHandler(ignoreCancelled = true)
public void onChannelMessage(PreChatFormatEvent event) {
// TODO: event.setFailureMessage
Object town = event.getChannel().getContext(KEY);
try {
final Resident resident = TownyAPI.getInstance().getDataSource().getResident(user1.player().getName());
if ((town instanceof Boolean) && ((Boolean) town)) {
if (!isInTown(event.getUser())) {
event.setCancelled(true);
}
}
if (resident.hasTown()) {
return resident.getTown().hasResident(user2.player().getName());
}
} catch (final NotRegisteredException exception) {
exception.printStackTrace();
}
@EventHandler
public void onResidentRemove(TownRemoveResidentEvent event) {
String name = event.getResident().getName();
ChatUser user = carbonChat.getUserService().wrap(name);
Object town = user.getSelectedChannel().getContext(KEY);
if ((town instanceof Boolean) && ((Boolean) town)) {
user.clearSelectedChannel();
}
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
ChatUser user = carbonChat.getUserService().wrap(event.getPlayer());
Object town = user.getSelectedChannel().getContext(KEY);
if ((town instanceof Boolean) && ((Boolean) town) && !isInTown(user)) {
user.clearSelectedChannel();
}
}
public boolean isInTown(@NonNull ChatUser user) {
try {
return TownyAPI.getInstance().getDataSource().getResident(user.asPlayer().getName()).hasTown();
} catch (NotRegisteredException e) {
e.printStackTrace();
}
return false;
}
public boolean isInSameTown(@NonNull ChatUser user1, @NonNull ChatUser user2) {
if (!user1.isOnline() || !user2.isOnline()) {
return false;
}
try {
Resident resident = TownyAPI.getInstance().getDataSource().getResident(user1.asPlayer().getName());
if (resident.hasTown()) {
return resident.getTown().hasResident(user2.asPlayer().getName());
}
} catch (NotRegisteredException e) {
e.printStackTrace();
}
return false;
}
return false;
}
}
@@ -21,112 +21,112 @@ import java.util.List;
public final class WorldGuardContext implements Listener {
@NonNull
private static final String KEY = "worldguard-region";
@NonNull
private static final String KEY = "worldguard-region";
public WorldGuardContext(@NonNull CarbonChat carbonChat) {
carbonChat.getContextManager().register(KEY, (context) -> {
return this.testContext(context.getSender(), context.getTarget(), context.getValue());
});
public WorldGuardContext(@NonNull final CarbonChat carbonChat) {
carbonChat.contextManager().register(KEY, context -> {
return this.testContext(context.sender(), context.target(), context.value());
});
}
@EventHandler(ignoreCancelled = true)
public void onChannelSwitch(final ChannelSwitchEvent event) {
// TODO: cancellation message
final Object value = event.channel().context(KEY);
if ((value instanceof String || value instanceof List) && !this.isInRegionOrRegions(value, event.user())) {
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled = true)
public void onChannelMessage(final PreChatFormatEvent event) {
// TODO: cancellation message
final Object value = event.channel().context(KEY);
if ((value instanceof String || value instanceof List) && !this.isInRegionOrRegions(value, event.user())) {
event.setCancelled(true);
}
}
private boolean isInRegionOrRegions(@Nullable final Object value, @NonNull final ChatUser user) {
if (value instanceof String) {
return this.isInRegion((String) value, user);
}
@EventHandler(ignoreCancelled = true)
public void onChannelSwitch(ChannelSwitchEvent event) {
// TODO: cancellation message
Object value = event.getChannel().getContext(KEY);
if ((value instanceof String || value instanceof List) && !isInRegionOrRegions(value, event.getUser())) {
event.setCancelled(true);
if (value instanceof List) {
for (final String region : (List<String>) value) {
if (this.isInRegion(region, user)) {
return true;
}
}
}
@EventHandler(ignoreCancelled = true)
public void onChannelMessage(PreChatFormatEvent event) {
// TODO: cancellation message
Object value = event.getChannel().getContext(KEY);
return false;
}
if ((value instanceof String || value instanceof List) && !isInRegionOrRegions(value, event.getUser())) {
event.setCancelled(true);
}
}
public boolean testContext(@NonNull final ChatUser sender, @NonNull final ChatUser target, @Nullable final Object value) {
boolean user1InRegion = false;
boolean user2InRegion = false;
private boolean isInRegionOrRegions(@Nullable Object value, @NonNull ChatUser user) {
if (value instanceof String) {
return isInRegion((String) value, user);
if (value instanceof Boolean && (Boolean) value) {
return this.isInSameRegion(sender, target);
} else if (value instanceof String) {
user1InRegion = this.isInRegion((String) value, sender);
user2InRegion = this.isInRegion((String) value, target);
} else if (value instanceof List) {
for (final String item : (List<String>) value) {
if (!user1InRegion) {
user1InRegion = this.isInRegion(item, sender);
}
if (value instanceof List) {
for (String region : ((List<String>) value)) {
if (isInRegion(region, user)) {
return true;
}
}
if (!user2InRegion) {
user2InRegion = this.isInRegion(item, target);
}
return false;
}
} else {
return true;
}
public boolean testContext(@NonNull ChatUser sender, @NonNull ChatUser target, @Nullable Object value) {
boolean user1InRegion = false;
boolean user2InRegion = false;
return user1InRegion && user2InRegion;
}
if (value instanceof Boolean && (Boolean) value) {
return isInSameRegion(sender, target);
} else if (value instanceof String) {
user1InRegion = isInRegion((String) value, sender);
user2InRegion = isInRegion((String) value, target);
} else if (value instanceof List) {
for (String item : (List<String>) value) {
if (!user1InRegion) {
user1InRegion = isInRegion(item, sender);
}
if (!user2InRegion) {
user2InRegion = isInRegion(item, target);
}
}
} else {
return true;
}
return user1InRegion && user2InRegion;
public boolean isInSameRegion(@NonNull final ChatUser user1, @NonNull final ChatUser user2) {
if (!user1.online() || !user2.online()) {
return false;
}
public boolean isInSameRegion(@NonNull ChatUser user1, @NonNull ChatUser user2) {
if (!user1.isOnline() || !user2.isOnline()) {
return false;
}
final Location user1Location = BukkitAdapter.adapt(user1.player().getLocation());
final Location user2Location = BukkitAdapter.adapt(user2.player().getLocation());
Location user1Location = BukkitAdapter.adapt(user1.asPlayer().getLocation());
Location user2Location = BukkitAdapter.adapt(user2.asPlayer().getLocation());
final RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer();
final RegionQuery regionQuery = container.createQuery();
RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer();
RegionQuery regionQuery = container.createQuery();
final ApplicableRegionSet user1Regions = regionQuery.getApplicableRegions(user1Location);
final ApplicableRegionSet user2Regions = regionQuery.getApplicableRegions(user2Location);
ApplicableRegionSet user1Regions = regionQuery.getApplicableRegions(user1Location);
ApplicableRegionSet user2Regions = regionQuery.getApplicableRegions(user2Location);
for (ProtectedRegion region : user1Regions) {
if (user2Regions.getRegions().contains(region)) {
return true;
}
}
return false;
for (final ProtectedRegion region : user1Regions) {
if (user2Regions.getRegions().contains(region)) {
return true;
}
}
public boolean isInRegion(@NonNull String region, @NonNull ChatUser user) {
RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer();
World world = BukkitAdapter.adapt(user.asPlayer().getWorld());
ProtectedRegion protection = container.get(world).getRegion(region);
return false;
}
return isInRegion(protection, user);
}
public boolean isInRegion(@NonNull final String region, @NonNull final ChatUser user) {
final RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer();
final World world = BukkitAdapter.adapt(user.player().getWorld());
final ProtectedRegion protection = container.get(world).getRegion(region);
public boolean isInRegion(@NonNull ProtectedRegion region, @NonNull ChatUser user) {
Location location = BukkitAdapter.adapt(user.asPlayer().getLocation());
return this.isInRegion(protection, user);
}
return region.contains(location.getBlockX(), location.getBlockY(), location.getBlockZ());
}
public boolean isInRegion(@NonNull final ProtectedRegion region, @NonNull final ChatUser user) {
final org.bukkit.Location location = user.player().getLocation();
return region.contains(location.getBlockX(), location.getBlockY(), location.getBlockZ());
}
}
@@ -13,81 +13,81 @@ import org.checkerframework.checker.nullness.qual.NonNull;
public final class mcMMOContext implements Listener {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public mcMMOContext(@NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
public mcMMOContext(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat;
this.carbonChat.getContextManager().register("mcmmo-party", (context) -> {
if ((context.getValue() instanceof Boolean) && ((Boolean) context.getValue())) {
return isInSameParty(context.getSender(), context.getTarget());
}
this.carbonChat.contextManager().register("mcmmo-party", context -> {
if ((context.value() instanceof Boolean) && ((Boolean) context.value())) {
return this.isInSameParty(context.sender(), context.target());
}
return true;
});
return true;
});
}
@EventHandler(ignoreCancelled = true)
public void onChannelSwitch(final ChannelSwitchEvent event) {
final Object party = event.channel().context("mcmmo-party");
if ((party instanceof Boolean) && ((Boolean) party)) {
if (!this.isInParty(event.user())) {
event.setCancelled(true);
event.failureMessage(this.carbonChat.getConfig().getString("contexts.mcMMO.cancellation-message"));
}
}
}
@EventHandler(ignoreCancelled = true)
public void onChannelMessage(final PreChatFormatEvent event) {
final Object party = event.channel().context("mcmmo-party");
if ((party instanceof Boolean) && ((Boolean) party)) {
if (!this.isInParty(event.user())) {
event.setCancelled(true);
}
}
}
private static final McMMOPartyChangeEvent.EventReason LEFT = McMMOPartyChangeEvent.EventReason.LEFT_PARTY;
private static final McMMOPartyChangeEvent.EventReason KICKED = McMMOPartyChangeEvent.EventReason.KICKED_FROM_PARTY;
@EventHandler(ignoreCancelled = true)
public void onPartyLeave(final McMMOPartyChangeEvent event) {
if (event.getReason() != LEFT && event.getReason() != KICKED) {
return;
}
@EventHandler(ignoreCancelled = true)
public void onChannelSwitch(ChannelSwitchEvent event) {
Object party = event.getChannel().getContext("mcmmo-party");
final ChatUser user = this.carbonChat.userService().wrap(event.getPlayer());
final Object party = user.selectedChannel().context("mcmmo-party");
if ((party instanceof Boolean) && ((Boolean) party)) {
if (!isInParty(event.getUser())) {
event.setCancelled(true);
event.setFailureMessage(carbonChat.getConfig().getString("contexts.mcMMO.cancellation-message"));
}
}
if ((party instanceof Boolean) && ((Boolean) party)) {
user.clearSelectedChannel();
}
}
@EventHandler
public void onPlayerJoin(final PlayerJoinEvent event) {
final ChatUser user = this.carbonChat.userService().wrap(event.getPlayer());
final Object party = user.selectedChannel().context("mcmmo-party");
if ((party instanceof Boolean) && ((Boolean) party) && !this.isInParty(user)) {
user.clearSelectedChannel();
}
}
public boolean isInParty(@NonNull final ChatUser user) {
return PartyAPI.inParty(user.player());
}
public boolean isInSameParty(@NonNull final ChatUser user1, @NonNull final ChatUser user2) {
if (!user1.online() || !user2.online()) {
return false;
}
@EventHandler(ignoreCancelled = true)
public void onChannelMessage(PreChatFormatEvent event) {
Object party = event.getChannel().getContext("mcmmo-party");
if ((party instanceof Boolean) && ((Boolean) party)) {
if (!isInParty(event.getUser())) {
event.setCancelled(true);
}
}
}
private final McMMOPartyChangeEvent.EventReason LEFT = McMMOPartyChangeEvent.EventReason.LEFT_PARTY;
private final McMMOPartyChangeEvent.EventReason KICKED = McMMOPartyChangeEvent.EventReason.KICKED_FROM_PARTY;
@EventHandler(ignoreCancelled = true)
public void onPartyLeave(McMMOPartyChangeEvent event) {
if (event.getReason() != LEFT && event.getReason() != KICKED) {
return;
}
ChatUser user = carbonChat.getUserService().wrap(event.getPlayer());
Object party = user.getSelectedChannel().getContext("mcmmo-party");
if ((party instanceof Boolean) && ((Boolean) party)) {
user.clearSelectedChannel();
}
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
ChatUser user = carbonChat.getUserService().wrap(event.getPlayer());
Object party = user.getSelectedChannel().getContext("mcmmo-party");
if ((party instanceof Boolean) && ((Boolean) party) && !isInParty(user)) {
user.clearSelectedChannel();
}
}
public boolean isInParty(@NonNull ChatUser user) {
return PartyAPI.inParty(user.asPlayer());
}
public boolean isInSameParty(@NonNull ChatUser user1, @NonNull ChatUser user2) {
if (!user1.isOnline() || !user2.isOnline()) {
return false;
}
return PartyAPI.inSameParty(user1.asPlayer(), user2.asPlayer());
}
return PartyAPI.inSameParty(user1.player(), user2.player());
}
}
File diff suppressed because it is too large. Load diff
@@ -15,75 +15,75 @@ import java.util.LinkedHashMap;
public class AliasedChannelCommand {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final ChatChannel chatChannel;
@NonNull
private final ChatChannel chatChannel;
@NonNull
private final String commandName;
@NonNull
private final String commandName;
public AliasedChannelCommand(@NonNull CarbonChat carbonChat, @NonNull ChatChannel chatChannel) {
this.carbonChat = carbonChat;
this.chatChannel = chatChannel;
public AliasedChannelCommand(@NonNull final CarbonChat carbonChat, @NonNull final ChatChannel chatChannel) {
this.carbonChat = carbonChat;
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)
.withArguments(setChannelArguments)
.withPermission(CommandPermission.fromString("carbonchat.channel"))
.executesPlayer(this::setChannel)
.register();
new CommandAPICommand(this.commandName)
.withArguments(setChannelArguments)
.withPermission(CommandPermission.fromString("carbonchat.channel"))
.executesPlayer(this::channel)
.register();
LinkedHashMap<String, Argument> sendMessageArguments = new LinkedHashMap<>();
sendMessageArguments.put("message", new GreedyStringArgument());
final LinkedHashMap<String, Argument> sendMessageArguments = new LinkedHashMap<>();
sendMessageArguments.put("message", new GreedyStringArgument());
new CommandAPICommand(commandName)
.withArguments(sendMessageArguments)
.withPermission(CommandPermission.fromString("carbonchat.channel.message"))
.executesPlayer(this::sendMessage)
.register();
new CommandAPICommand(this.commandName)
.withArguments(sendMessageArguments)
.withPermission(CommandPermission.fromString("carbonchat.channel.message"))
.executesPlayer(this::sendMessage)
.register();
}
private void channel(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final ChatUser user = this.carbonChat.userService().wrap(player);
if (user.channelSettings(this.chatChannel()).ignored()) {
user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, this.chatChannel().cannotUseMessage(),
"br", "\n",
"color", "<" + this.chatChannel().channelColor(user).toString() + ">",
"channel", this.chatChannel().name()));
return;
}
private void setChannel(@NonNull Player player, @NonNull Object @NonNull [] args) {
ChatUser user = carbonChat.getUserService().wrap(player);
user.selectedChannel(this.chatChannel());
if (user.getChannelSettings(getChatChannel()).isIgnored()) {
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, getChatChannel().getCannotUseMessage(),
"br", "\n",
"color", "<" + getChatChannel().getChannelColor(user).toString() + ">",
"channel", getChatChannel().getName()));
user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, this.chatChannel().switchMessage(),
"br", "\n",
"color", "<" + this.chatChannel().channelColor(user).toString() + ">",
"channel", this.chatChannel().name()));
}
return;
}
private void sendMessage(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final ChatUser user = this.carbonChat.userService().wrap(player);
final String message = (String) args[0];
user.setSelectedChannel(getChatChannel());
final Component component = this.chatChannel().sendMessage(user, message, false);
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, getChatChannel().getSwitchMessage(),
"br", "\n",
"color", "<" + getChatChannel().getChannelColor(user).toString() + ">",
"channel", getChatChannel().getName()));
}
this.carbonChat.adventureManager().audiences().console().sendMessage(component);
}
private void sendMessage(@NonNull Player player, @NonNull Object @NonNull [] args) {
ChatUser user = carbonChat.getUserService().wrap(player);
String message = (String) args[0];
@NonNull
public ChatChannel chatChannel() {
return this.chatChannel;
}
Component component = getChatChannel().sendMessage(user, message, false);
carbonChat.getAdventureManager().getAudiences().console().sendMessage(component);
}
@NonNull
public ChatChannel getChatChannel() {
return chatChannel;
}
@NonNull
public String getCommandName() {
return commandName;
}
@NonNull
public String commandName() {
return this.commandName;
}
}
@@ -18,69 +18,69 @@ import java.util.LinkedHashMap;
public class ChannelCommand {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public ChannelCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) {
this.carbonChat = carbonChat;
public ChannelCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) {
return;
}
CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> setChannelArguments = new LinkedHashMap<>();
setChannelArguments.put("channel", CarbonUtils.channelArgument());
new CommandAPICommand(commandSettings.getName())
.withArguments(setChannelArguments)
.withAliases(commandSettings.getAliasesArray())
.withPermission(CommandPermission.fromString("carbonchat.channel"))
.executesPlayer(this::setChannel)
.register();
LinkedHashMap<String, Argument> sendMessageArguments = new LinkedHashMap<>();
sendMessageArguments.put("channel", CarbonUtils.channelArgument());
sendMessageArguments.put("message", new GreedyStringArgument());
new CommandAPICommand(commandSettings.getName())
.withArguments(sendMessageArguments)
.withAliases(commandSettings.getAliasesArray())
.withPermission(CommandPermission.fromString("carbonchat.channel.message"))
.executesPlayer(this::sendMessage)
.register();
if (!commandSettings.enabled()) {
return;
}
private void setChannel(@NonNull Player player, @NonNull Object @NonNull [] args) {
ChatUser user = carbonChat.getUserService().wrap(player);
ChatChannel channel = (ChatChannel) args[0];
CommandUtils.handleDuplicateCommands(commandSettings);
if (user.getChannelSettings(channel).isIgnored()) {
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, channel.getCannotUseMessage(),
"br", "\n",
"color", "<" + channel.getChannelColor(user).toString() + ">",
"channel", channel.getName()));
final LinkedHashMap<String, Argument> setChannelArguments = new LinkedHashMap<>();
setChannelArguments.put("channel", CarbonUtils.channelArgument());
return;
}
new CommandAPICommand(commandSettings.name())
.withArguments(setChannelArguments)
.withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.channel"))
.executesPlayer(this::channel)
.register();
user.setSelectedChannel(channel);
final LinkedHashMap<String, Argument> sendMessageArguments = new LinkedHashMap<>();
sendMessageArguments.put("channel", CarbonUtils.channelArgument());
sendMessageArguments.put("message", new GreedyStringArgument());
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, channel.getSwitchMessage(),
"br", "\n",
"color", "<" + channel.getChannelColor(user).toString() + ">",
"channel", channel.getName()));
new CommandAPICommand(commandSettings.name())
.withArguments(sendMessageArguments)
.withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.channel.message"))
.executesPlayer(this::sendMessage)
.register();
}
private void channel(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final ChatUser user = this.carbonChat.userService().wrap(player);
final ChatChannel channel = (ChatChannel) args[0];
if (user.channelSettings(channel).ignored()) {
user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, channel.cannotUseMessage(),
"br", "\n",
"color", "<" + channel.channelColor(user).toString() + ">",
"channel", channel.name()));
return;
}
private void sendMessage(@NonNull Player player, @NonNull Object @NonNull [] args) {
ChatUser user = carbonChat.getUserService().wrap(player);
ChatChannel channel = (ChatChannel) args[0];
String message = (String) args[1];
user.selectedChannel(channel);
Component component = channel.sendMessage(user, message, false);
user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, channel.switchMessage(),
"br", "\n",
"color", "<" + channel.channelColor(user).toString() + ">",
"channel", channel.name()));
}
carbonChat.getAdventureManager().getAudiences().console().sendMessage(component);
}
private void sendMessage(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final ChatUser user = this.carbonChat.userService().wrap(player);
final ChatChannel channel = (ChatChannel) args[0];
final String message = (String) args[1];
final Component component = channel.sendMessage(user, message, false);
this.carbonChat.adventureManager().audiences().console().sendMessage(component);
}
}
@@ -24,113 +24,113 @@ import java.util.regex.Pattern;
public class ChannelListCommand {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public ChannelListCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) {
this.carbonChat = carbonChat;
public ChannelListCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) {
return;
}
CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>();
new CommandAPICommand(commandSettings.getName())
.withArguments(channelArguments)
.withAliases(commandSettings.getAliasesArray())
.withPermission(CommandPermission.fromString("carbonchat.channellist"))
.executesPlayer(this::executeSelf)
.register();
LinkedHashMap<String, Argument> argumentsOther = new LinkedHashMap<>();
argumentsOther.put("player", CarbonUtils.onlineChatUserArgument());
new CommandAPICommand(commandSettings.getName())
.withArguments(argumentsOther)
.withAliases(commandSettings.getAliasesArray())
.withPermission(CommandPermission.fromString("carbonchat.channellist.other"))
.executes(this::executeOther)
.register();
if (!commandSettings.enabled()) {
return;
}
public void executeSelf(@NonNull Player player, @NonNull Object @NonNull [] args) {
Iterator<ChatChannel> allChannels = carbonChat.getChannelManager().getRegistry().values().iterator();
ChatUser user = carbonChat.getUserService().wrap(player);
CommandUtils.handleDuplicateCommands(commandSettings);
getListAndSend(player, user, allChannels);
final LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>();
new CommandAPICommand(commandSettings.name())
.withArguments(channelArguments)
.withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.channellist"))
.executesPlayer(this::executeSelf)
.register();
final LinkedHashMap<String, Argument> argumentsOther = new LinkedHashMap<>();
argumentsOther.put("player", CarbonUtils.onlineChatUserArgument());
new CommandAPICommand(commandSettings.name())
.withArguments(argumentsOther)
.withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.channellist.other"))
.executes(this::executeOther)
.register();
}
public void executeSelf(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final Iterator<ChatChannel> allChannels = this.carbonChat.channelManager().registry().values().iterator();
final ChatUser user = this.carbonChat.userService().wrap(player);
this.listAndSend(player, user, allChannels);
}
public void executeOther(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
final Audience cmdSender = this.carbonChat.adventureManager().audiences().audience(sender);
final ChatUser user = (ChatUser) args[0];
if (!user.online()) {
final String mustBeOnline = this.carbonChat.language().getString("user-must-be-online");
cmdSender.sendMessage(this.carbonChat.adventureManager().processMessage(mustBeOnline, "br", "\n", "player", user.offlinePlayer().getName()));
return;
}
public void executeOther(@NonNull CommandSender sender, @NonNull Object @NonNull [] args) {
Audience cmdSender = carbonChat.getAdventureManager().getAudiences().audience(sender);
ChatUser user = (ChatUser) args[0];
final Iterator<ChatChannel> allChannels = this.carbonChat.channelManager().registry().values().iterator();
this.listAndSend(sender, user, allChannels);
}
if (!user.isOnline()) {
String mustBeOnline = carbonChat.getLanguage().getString("user-must-be-online");
cmdSender.sendMessage(carbonChat.getAdventureManager().processMessage(mustBeOnline, "br", "\n", "player", user.asOfflinePlayer().getName()));
return;
}
private void listAndSend(@NonNull final CommandSender sender, @NonNull final ChatUser user,
@NonNull final Iterator<ChatChannel> allChannels) {
ChatChannel channel;
final List<ChatChannel> canSee = new ArrayList<>();
final List<ChatChannel> cannotSee = new ArrayList<>();
Iterator<ChatChannel> allChannels = carbonChat.getChannelManager().getRegistry().values().iterator();
getListAndSend(sender, user, allChannels);
while (allChannels.hasNext()) {
channel = allChannels.next();
if (channel.canPlayerSee(user, true)) {
canSee.add(channel);
} else {
cannotSee.add(channel);
}
}
private void getListAndSend(@NonNull CommandSender sender, @NonNull ChatUser user, @NonNull Iterator<ChatChannel> allChannels) {
ChatChannel channel;
List<ChatChannel> canSee = new ArrayList<>();
List<ChatChannel> cannotSee = new ArrayList<>();
final Iterator<ChatChannel> visibleChannels = canSee.iterator();
final TextComponent.Builder availableList = TextComponent.builder("");
while (allChannels.hasNext()) {
channel = allChannels.next();
this.makeList(visibleChannels, availableList);
if (channel.canPlayerSee(user, true)) {
canSee.add(channel);
} else {
cannotSee.add(channel);
}
}
final String availableFormat = this.carbonChat.language().getString("available-channels-list");
Component availableComponent = this.carbonChat.adventureManager().processMessage(availableFormat, "br", "\n");
availableComponent = availableComponent.replaceFirstText(Pattern.compile(Pattern.quote("<list>")), ac -> availableList);
Iterator<ChatChannel> visibleChannels = canSee.iterator();
TextComponent.Builder availableList = TextComponent.builder("");
final Audience audience = this.carbonChat.adventureManager().audiences().audience(sender);
makeList(visibleChannels, availableList);
audience.sendMessage(availableComponent);
String availableFormat = carbonChat.getLanguage().getString("available-channels-list");
Component availableComponent = carbonChat.getAdventureManager().processMessage(availableFormat, "br", "\n");
availableComponent = availableComponent.replaceFirstText(Pattern.compile(Pattern.quote("<list>")), (ac) -> availableList);
if (sender.hasPermission("carbonchat.channellist.bypass") && !cannotSee.isEmpty()) {
final Iterator<ChatChannel> invisibleChannels = cannotSee.iterator();
final TextComponent.Builder unavailableList = TextComponent.builder("");
Audience audience = carbonChat.getAdventureManager().getAudiences().audience(sender);
this.makeList(invisibleChannels, unavailableList);
audience.sendMessage(availableComponent);
final String unavailableFormat = this.carbonChat.language().getString("unavailable-channels-list");
Component unavailableComponent = this.carbonChat.adventureManager().processMessage(unavailableFormat, "br", "\n");
unavailableComponent = unavailableComponent.replaceFirstText(Pattern.compile(Pattern.quote("<list>")), uac -> unavailableList);
if (sender.hasPermission("carbonchat.channellist.bypass") && !cannotSee.isEmpty()) {
Iterator<ChatChannel> invisibleChannels = cannotSee.iterator();
TextComponent.Builder unavailableList = TextComponent.builder("");
makeList(invisibleChannels, unavailableList);
String unavailableFormat = carbonChat.getLanguage().getString("unavailable-channels-list");
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) {
String listSeparator = carbonChat.getLanguage().getString("channel-list-separator", ", ");
// TODO: Larry, why did you double assign the listSeparatorComponent?
Component listSeparatorComponent = TextComponent.of(listSeparator);
private void makeList(@NonNull final Iterator<@NonNull ChatChannel> iterator, final TextComponent.@NonNull Builder list) {
final String listSeparator = this.carbonChat.language().getString("channel-list-separator", ", ");
// TODO: Larry, why did you double assign the listSeparatorComponent?
final Component listSeparatorComponent = TextComponent.of(listSeparator);
while (iterator.hasNext()) {
ChatChannel channel = iterator.next();
list.append(TextComponent.of(channel.getName()));
if (iterator.hasNext()) {
list.append(listSeparatorComponent);
}
}
while (iterator.hasNext()) {
list.append(TextComponent.of(iterator.next().name()));
if (iterator.hasNext()) {
list.append(listSeparatorComponent);
}
}
}
}
@@ -11,33 +11,33 @@ import org.checkerframework.checker.nullness.qual.NonNull;
public class ChatReloadCommand {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public ChatReloadCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) {
this.carbonChat = carbonChat;
public ChatReloadCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) {
return;
}
CommandUtils.handleDuplicateCommands(commandSettings);
new CommandAPICommand(commandSettings.getName())
.withAliases(commandSettings.getAliasesArray())
.withPermission(CommandPermission.fromString("carbonchat.reload"))
.executes(this::execute)
.register();
if (!commandSettings.enabled()) {
return;
}
private void execute(@NonNull CommandSender sender, @NonNull Object @NonNull [] args) {
carbonChat.reloadConfig();
carbonChat.reloadFilters();
CommandUtils.handleDuplicateCommands(commandSettings);
Component message = carbonChat.getAdventureManager().processMessage(carbonChat.getLanguage().getString("reloaded"),
"br", "\n");
new CommandAPICommand(commandSettings.name())
.withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.reload"))
.executes(this::execute)
.register();
}
carbonChat.getAdventureManager().getAudiences().audience(sender).sendMessage(message);
}
private void execute(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
this.carbonChat.reloadConfig();
this.carbonChat.reloadFilters();
final Component message = this.carbonChat.adventureManager()
.processMessage(this.carbonChat.language().getString("reloaded"), "br", "\n");
this.carbonChat.adventureManager().audiences().audience(sender).sendMessage(message);
}
}
@@ -1,6 +1,5 @@
package net.draycia.carbon.commands;
import dev.jorel.commandapi.CommandAPICommand;
import dev.jorel.commandapi.CommandPermission;
import net.draycia.carbon.CarbonChat;
@@ -15,46 +14,46 @@ import org.checkerframework.checker.nullness.qual.NonNull;
public class ClearChatCommand {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public ClearChatCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) {
this.carbonChat = carbonChat;
public ClearChatCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) {
return;
}
CommandUtils.handleDuplicateCommands(commandSettings);
new CommandAPICommand(commandSettings.getName())
.withAliases(commandSettings.getAliasesArray())
.withPermission(CommandPermission.fromString("carbonchat.clearchat.clear"))
.executes(this::execute)
.register();
if (!commandSettings.enabled()) {
return;
}
private void execute(@NonNull CommandSender sender, @NonNull Object @NonNull [] args) {
String format = carbonChat.getModConfig().getString("clear-chat.message", "");
Component component = carbonChat.getAdventureManager().processMessage(format, "br", "\n");
CommandUtils.handleDuplicateCommands(commandSettings);
for (Player player : Bukkit.getOnlinePlayers()) {
ChatUser audience = carbonChat.getUserService().wrap(player);
new CommandAPICommand(commandSettings.name())
.withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.clearchat.clear"))
.executes(this::execute)
.register();
}
if (player.hasPermission("carbonchat.clearchat.exempt")) {
String message = carbonChat.getLanguage().getString("clear-exempt");
audience.sendMessage(carbonChat.getAdventureManager().processMessage(message, "player", sender.getName()));
} else {
for (int i = 0; i < carbonChat.getModConfig().getInt("clear-chat.message-count", 100); i++) {
audience.sendMessage(component);
}
}
private void execute(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
final String format = this.carbonChat.moderationConfig().getString("clear-chat.message", "");
final Component component = this.carbonChat.adventureManager().processMessage(format, "br", "\n");
if (player.hasPermission("carbonchat.clearchat.notify")) {
String message = carbonChat.getLanguage().getString("clear-notify");
audience.sendMessage(carbonChat.getAdventureManager().processMessage(message, "player", sender.getName()));
}
for (final Player player : Bukkit.getOnlinePlayers()) {
final ChatUser audience = this.carbonChat.userService().wrap(player);
if (player.hasPermission("carbonchat.clearchat.exempt")) {
final String message = this.carbonChat.language().getString("clear-exempt");
audience.sendMessage(this.carbonChat.adventureManager().processMessage(message, "player", sender.getName()));
} else {
for (int i = 0; i < this.carbonChat.moderationConfig().getInt("clear-chat.message-count", 100); i++) {
audience.sendMessage(component);
}
}
if (player.hasPermission("carbonchat.clearchat.notify")) {
final String message = this.carbonChat.language().getString("clear-notify");
audience.sendMessage(this.carbonChat.adventureManager().processMessage(message, "player", sender.getName()));
}
}
}
}
@@ -18,58 +18,58 @@ import java.util.LinkedHashMap;
public class IgnoreCommand {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public IgnoreCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) {
this.carbonChat = carbonChat;
public IgnoreCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) {
return;
}
CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>();
channelArguments.put("player", CarbonUtils.chatUserArgument());
new CommandAPICommand(commandSettings.getName())
.withArguments(channelArguments)
.withAliases(commandSettings.getAliasesArray())
.withPermission(CommandPermission.fromString("carbonchat.ignore"))
.executesPlayer(this::execute)
.register();
if (!commandSettings.enabled()) {
return;
}
private void execute(@NonNull Player player, @NonNull Object @NonNull [] args) {
ChatUser targetUser = (ChatUser) args[0];
ChatUser user = carbonChat.getUserService().wrap(player);
CommandUtils.handleDuplicateCommands(commandSettings);
if (user.isIgnoringUser(targetUser)) {
user.setIgnoringUser(targetUser, false);
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player,
carbonChat.getLanguage().getString("not-ignoring-user"),
"br", "\n", "player", targetUser.asOfflinePlayer().getName()));
final LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>();
channelArguments.put("player", CarbonUtils.chatUserArgument());
new CommandAPICommand(commandSettings.name())
.withArguments(channelArguments)
.withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.ignore"))
.executesPlayer(this::execute)
.register();
}
private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final ChatUser targetUser = (ChatUser) args[0];
final ChatUser user = this.carbonChat.userService().wrap(player);
if (user.ignoringUser(targetUser)) {
user.ignoringUser(targetUser, false);
user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player,
this.carbonChat.language().getString("not-ignoring-user"),
"br", "\n", "player", targetUser.offlinePlayer().getName()));
} else {
Bukkit.getScheduler().runTaskAsynchronously(this.carbonChat, () -> {
final Permission permission = this.carbonChat.permission();
final String format;
if (permission.playerHas(null, targetUser.offlinePlayer(), "carbonchat.ignore.exempt")) {
format = this.carbonChat.language().getString("ignore-exempt");
} else {
Bukkit.getScheduler().runTaskAsynchronously(carbonChat, () -> {
Permission permission = carbonChat.getPermission();
String format;
if (permission.playerHas(null, targetUser.asOfflinePlayer(), "carbonchat.ignore.exempt")) {
format = carbonChat.getLanguage().getString("ignore-exempt");
} else {
user.setIgnoringUser(targetUser, true);
format = carbonChat.getLanguage().getString("ignoring-user");
}
Component message = carbonChat.getAdventureManager().processMessageWithPapi(player, format,
"br", "\n", "sender", player.getDisplayName(), "player",
targetUser.asOfflinePlayer().getName());
user.sendMessage(message);
});
user.ignoringUser(targetUser, true);
format = this.carbonChat.language().getString("ignoring-user");
}
final Component message = this.carbonChat.adventureManager().processMessageWithPapi(player, format,
"br", "\n", "sender", player.getDisplayName(), "player",
targetUser.offlinePlayer().getName());
user.sendMessage(message);
});
}
}
}
@@ -18,53 +18,53 @@ import java.util.LinkedHashMap;
public class MeCommand {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public MeCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) {
this.carbonChat = carbonChat;
public MeCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) {
return;
}
CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>();
channelArguments.put("message", new GreedyStringArgument());
new CommandAPICommand(commandSettings.getName())
.withArguments(channelArguments)
.withAliases(commandSettings.getAliasesArray())
.withPermission(CommandPermission.fromString("carbonchat.me"))
.executesPlayer(this::execute)
.register();
if (!commandSettings.enabled()) {
return;
}
private void execute(@NonNull Player player, @NonNull Object @NonNull [] args) {
String message = ((String) args[0]).replace("</pre>", "");
String format = PlaceholderAPI.setPlaceholders(player, carbonChat.getLanguage().getString("me"));
CommandUtils.handleDuplicateCommands(commandSettings);
if (!player.hasPermission("carbonchat.me.formatting")) {
format = format.replace("<message>", "<pre><message></pre>");
}
final LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>();
channelArguments.put("message", new GreedyStringArgument());
Component component = carbonChat.getAdventureManager().processMessage(format, "br", "\n",
"displayname", player.getDisplayName(), "message", message);
new CommandAPICommand(commandSettings.name())
.withArguments(channelArguments)
.withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.me"))
.executesPlayer(this::execute)
.register();
}
ChatUser user = carbonChat.getUserService().wrap(player);
private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final String message = ((String) args[0]).replace("</pre>", "");
String format = PlaceholderAPI.setPlaceholders(player, this.carbonChat.language().getString("me"));
if (user.isShadowMuted()) {
user.sendMessage(component);
} else {
for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
if (carbonChat.getUserService().wrap(onlinePlayer).isIgnoringUser(user)) {
continue;
}
carbonChat.getAdventureManager().getAudiences().player(onlinePlayer).sendMessage(component);
}
}
if (!player.hasPermission("carbonchat.me.formatting")) {
format = format.replace("<message>", "<pre><message></pre>");
}
final Component component = this.carbonChat.adventureManager().processMessage(format, "br", "\n",
"displayname", player.getDisplayName(), "message", message);
final ChatUser user = this.carbonChat.userService().wrap(player);
if (user.shadowMuted()) {
user.sendMessage(component);
} else {
for (final Player onlinePlayer : Bukkit.getOnlinePlayers()) {
if (this.carbonChat.userService().wrap(onlinePlayer).ignoringUser(user)) {
continue;
}
this.carbonChat.adventureManager().audiences().player(onlinePlayer).sendMessage(component);
}
}
}
}
@@ -16,37 +16,37 @@ import java.util.LinkedHashMap;
public class MessageCommand {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public MessageCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) {
this.carbonChat = carbonChat;
public MessageCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) {
return;
}
CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>();
arguments.put("player", CarbonUtils.chatUserArgument());
arguments.put("message", new GreedyStringArgument());
new CommandAPICommand(commandSettings.getName())
.withArguments(arguments)
.withAliases(commandSettings.getAliasesArray())
.withPermission(CommandPermission.fromString("carbonchat.message"))
.executesPlayer(this::execute)
.register();
if (!commandSettings.enabled()) {
return;
}
private void execute(@NonNull Player player, @NonNull Object @NonNull [] args) {
ChatUser targetUser = (ChatUser) args[0];
String message = (String) args[1];
CommandUtils.handleDuplicateCommands(commandSettings);
ChatUser sender = carbonChat.getUserService().wrap(player);
final LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>();
arguments.put("player", CarbonUtils.chatUserArgument());
arguments.put("message", new GreedyStringArgument());
targetUser.sendMessage(sender, message);
}
new CommandAPICommand(commandSettings.name())
.withArguments(arguments)
.withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.message"))
.executesPlayer(this::execute)
.register();
}
private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final ChatUser targetUser = (ChatUser) args[0];
final String message = (String) args[1];
final ChatUser sender = this.carbonChat.userService().wrap(player);
targetUser.sendMessage(sender, message);
}
}
@@ -19,58 +19,58 @@ import java.util.LinkedHashMap;
public class MuteCommand {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public MuteCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) {
this.carbonChat = carbonChat;
public MuteCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) {
return;
}
CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>();
arguments.put("player", CarbonUtils.chatUserArgument());
new CommandAPICommand(commandSettings.getName())
.withArguments(arguments)
.withAliases(commandSettings.getAliasesArray())
.withPermission(CommandPermission.fromString("carbonchat.mute"))
.executes(this::execute)
.register();
if (!commandSettings.enabled()) {
return;
}
private void execute(@NonNull CommandSender sender, @NonNull Object @NonNull [] args) {
ChatUser user = (ChatUser) args[0];
Audience audience = carbonChat.getAdventureManager().getAudiences().audience(sender);
CommandUtils.handleDuplicateCommands(commandSettings);
if (user.isShadowMuted()) {
user.setMuted(false);
String format = carbonChat.getLanguage().getString("no-longer-muted");
final LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>();
arguments.put("player", CarbonUtils.chatUserArgument());
Component message = carbonChat.getAdventureManager().processMessage(format, "br", "\n",
"player", user.asOfflinePlayer().getName());
new CommandAPICommand(commandSettings.name())
.withArguments(arguments)
.withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.mute"))
.executes(this::execute)
.register();
}
audience.sendMessage(message);
private void execute(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
final ChatUser user = (ChatUser) args[0];
final Audience audience = this.carbonChat.adventureManager().audiences().audience(sender);
if (user.shadowMuted()) {
user.muted(false);
final String format = this.carbonChat.language().getString("no-longer-muted");
final Component message = this.carbonChat.adventureManager().processMessage(format, "br", "\n",
"player", user.offlinePlayer().getName());
audience.sendMessage(message);
} else {
Bukkit.getScheduler().runTaskAsynchronously(this.carbonChat, () -> {
final Permission permission = this.carbonChat.permission();
final String format;
if (permission.playerHas(null, user.offlinePlayer(), "carbonchat.mute.exempt")) {
format = this.carbonChat.language().getString("mute-exempt");
} else {
Bukkit.getScheduler().runTaskAsynchronously(carbonChat, () -> {
Permission permission = carbonChat.getPermission();
String format;
if (permission.playerHas(null, user.asOfflinePlayer(), "carbonchat.mute.exempt")) {
format = carbonChat.getLanguage().getString("mute-exempt");
} else {
user.setMuted(true);
format = carbonChat.getLanguage().getString("is-now-muted");
}
Component message = carbonChat.getAdventureManager().processMessage(format, "br", "\n",
"player", user.asOfflinePlayer().getName());
audience.sendMessage(message);
});
user.muted(true);
format = this.carbonChat.language().getString("is-now-muted");
}
final Component message = this.carbonChat.adventureManager().processMessage(format, "br", "\n",
"player", user.offlinePlayer().getName());
audience.sendMessage(message);
});
}
}
}
@@ -18,86 +18,86 @@ import java.util.LinkedHashMap;
public class NicknameCommand {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public NicknameCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) {
this.carbonChat = carbonChat;
public NicknameCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) {
return;
}
CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> selfArguments = new LinkedHashMap<>();
selfArguments.put("nickname", new StringArgument());
new CommandAPICommand(commandSettings.getName())
.withArguments(selfArguments)
.withAliases(commandSettings.getAliasesArray())
.withPermission(CommandPermission.fromString("carbonchat.nickname"))
.executesPlayer(this::executeSelf)
.register();
LinkedHashMap<String, Argument> otherArguments = new LinkedHashMap<>();
otherArguments.put("player", CarbonUtils.chatUserArgument());
otherArguments.put("nickname", new StringArgument());
new CommandAPICommand(commandSettings.getName())
.withArguments(otherArguments)
.withAliases(commandSettings.getAliasesArray())
.withPermission(CommandPermission.fromString("carbonchat.nickname.others"))
.executes(this::executeOther)
.register();
if (!commandSettings.enabled()) {
return;
}
private void executeSelf(@NonNull Player player, @NonNull Object @NonNull [] args) {
String nickname = (String) args[0];
ChatUser sender = carbonChat.getUserService().wrap(player);
CommandUtils.handleDuplicateCommands(commandSettings);
if (nickname.equalsIgnoreCase("off") || nickname.equalsIgnoreCase(player.getName())) {
nickname = null;
}
final LinkedHashMap<String, Argument> selfArguments = new LinkedHashMap<>();
selfArguments.put("nickname", new StringArgument());
sender.setNickname(nickname);
new CommandAPICommand(commandSettings.name())
.withArguments(selfArguments)
.withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.nickname"))
.executesPlayer(this::executeSelf)
.register();
String message;
final LinkedHashMap<String, Argument> otherArguments = new LinkedHashMap<>();
otherArguments.put("player", CarbonUtils.chatUserArgument());
otherArguments.put("nickname", new StringArgument());
if (nickname == null) {
message = carbonChat.getLanguage().getString("nickname-reset");
} else {
message = carbonChat.getLanguage().getString("nickname-set");
}
new CommandAPICommand(commandSettings.name())
.withArguments(otherArguments)
.withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.nickname.others"))
.executes(this::executeOther)
.register();
}
sender.sendMessage(carbonChat.getAdventureManager().processMessage(
message, "nickname", nickname == null ? "" : nickname,
"user", sender.asOfflinePlayer().getName()));
private void executeSelf(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
String nickname = (String) args[0];
final ChatUser sender = this.carbonChat.userService().wrap(player);
if (nickname.equalsIgnoreCase("off") || nickname.equalsIgnoreCase(player.getName())) {
nickname = null;
}
private void executeOther(@NonNull CommandSender sender, @NonNull Object @NonNull [] args) {
Audience user = carbonChat.getAdventureManager().getAudiences().audience(sender);
ChatUser target = (ChatUser) args[0];
String nickname = (String) args[1];
sender.nickname(nickname);
if (nickname.equalsIgnoreCase("off") ||
nickname.equalsIgnoreCase(target.asOfflinePlayer().getName())) {
nickname = null;
}
final String message;
target.setNickname(nickname);
String message;
if (nickname == null) {
message = carbonChat.getLanguage().getString("other-nickname-reset");
} else {
message = carbonChat.getLanguage().getString("other-nickname-set");
}
user.sendMessage(carbonChat.getAdventureManager().processMessage(
message, "nickname", nickname == null ? "" : nickname,
"user", target.asOfflinePlayer().getName()));
if (nickname == null) {
message = this.carbonChat.language().getString("nickname-reset");
} else {
message = this.carbonChat.language().getString("nickname-set");
}
sender.sendMessage(this.carbonChat.adventureManager().processMessage(
message, "nickname", nickname == null ? "" : nickname,
"user", sender.offlinePlayer().getName()));
}
private void executeOther(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
final Audience user = this.carbonChat.adventureManager().audiences().audience(sender);
final ChatUser target = (ChatUser) args[0];
String nickname = (String) args[1];
if (nickname.equalsIgnoreCase("off") ||
nickname.equalsIgnoreCase(target.offlinePlayer().getName())) {
nickname = null;
}
target.nickname(nickname);
final String message;
if (nickname == null) {
message = this.carbonChat.language().getString("other-nickname-reset");
} else {
message = this.carbonChat.language().getString("other-nickname-set");
}
user.sendMessage(this.carbonChat.adventureManager().processMessage(
message, "nickname", nickname == null ? "" : nickname,
"user", target.offlinePlayer().getName()));
}
}
@@ -16,51 +16,55 @@ import java.util.LinkedHashMap;
public class ReplyCommand {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public ReplyCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) {
this.carbonChat = carbonChat;
public ReplyCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) {
return;
}
CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>();
arguments.put("message", new GreedyStringArgument());
new CommandAPICommand(commandSettings.getName())
.withArguments(arguments)
.withAliases(commandSettings.getAliasesArray())
.withPermission(CommandPermission.fromString("carbonchat.reply"))
.executesPlayer(this::execute)
.register();
if (!commandSettings.enabled()) {
return;
}
private void execute(@NonNull Player player, @NonNull Object @NonNull [] args) {
String input = (String) args[0];
CommandUtils.handleDuplicateCommands(commandSettings);
ChatUser user = carbonChat.getUserService().wrap(player);
final LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>();
arguments.put("message", new GreedyStringArgument());
if (input == null || input.isEmpty()) {
String message = carbonChat.getLanguage().getString("reply-message-blank");
Component component = carbonChat.getAdventureManager().processMessage(message, "br", "\n");
user.sendMessage(component);
return;
}
new CommandAPICommand(commandSettings.name())
.withArguments(arguments)
.withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.reply"))
.executesPlayer(this::execute)
.register();
}
if (user.getReplyTarget() == null) {
String message = carbonChat.getLanguage().getString("no-reply-target");
Component component = carbonChat.getAdventureManager().processMessage(message, "br", "\n");
user.sendMessage(component);
return;
}
private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final String input = (String) args[0];
ChatUser targetUser = carbonChat.getUserService().wrap(user.getReplyTarget());
final ChatUser user = this.carbonChat.userService().wrap(player);
targetUser.sendMessage(user, input);
if (input.isEmpty()) {
final String message = this.carbonChat.language().getString("reply-message-blank");
final Component component = this.carbonChat.adventureManager().processMessage(message, "br", "\n");
user.sendMessage(component);
return;
}
if (user.replyTarget() == null) {
final String message = this.carbonChat.language().getString("no-reply-target");
final Component component = this.carbonChat.adventureManager().processMessage(message, "br", "\n");
user.sendMessage(component);
return;
}
final ChatUser targetUser = this.carbonChat.userService().wrap(user.replyTarget());
targetUser.sendMessage(user, input);
}
}
@@ -2,7 +2,8 @@ package net.draycia.carbon.commands;
import dev.jorel.commandapi.CommandAPICommand;
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.channels.ChatChannel;
import net.draycia.carbon.storage.ChatUser;
@@ -17,51 +18,51 @@ import java.util.LinkedHashMap;
public class SetColorCommand {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public SetColorCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) {
this.carbonChat = carbonChat;
public SetColorCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) {
return;
}
CommandUtils.handleDuplicateCommands(commandSettings);
for (ChatChannel channel : carbonChat.getChannelManager().getRegistry().values()) {
LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>();
arguments.put("channel", new LiteralArgument(channel.getKey()));
arguments.put("color", CarbonUtils.textColorArgument());
new CommandAPICommand(commandSettings.getName())
.withArguments(arguments)
.withAliases(commandSettings.getAliasesArray())
.withPermission(CommandPermission.fromString("carbonchat.setcolor"))
.executesPlayer((player, args) -> {
TextColor color = (TextColor)args[0];
ChatUser user = carbonChat.getUserService().wrap(player);
if (!player.hasPermission("carbonchat.setcolor." + channel.getKey())) {
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player,
carbonChat.getLanguage().getString("cannot-set-color"),
"br", "\n", "input", color.asHexString(),
"channel", channel.getName()));
return;
}
UserChannelSettings settings = user.getChannelSettings(channel);
settings.setColor(color);
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player,
carbonChat.getLanguage().getString("channel-color-set"),
"br", "\n", "color", "<color:" + color.asHexString() + ">", "channel",
channel.getName(), "hex", color.asHexString()));
})
.register();
}
if (!commandSettings.enabled()) {
return;
}
CommandUtils.handleDuplicateCommands(commandSettings);
for (final ChatChannel channel : this.carbonChat.channelManager().registry().values()) {
final LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>();
arguments.put("channel", new LiteralArgument(channel.key()));
arguments.put("color", CarbonUtils.textColorArgument());
new CommandAPICommand(commandSettings.name())
.withArguments(arguments)
.withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.setcolor"))
.executesPlayer((player, args) -> {
final TextColor color = (TextColor) args[0];
final ChatUser user = this.carbonChat.userService().wrap(player);
if (!player.hasPermission("carbonchat.setcolor." + channel.key())) {
user.sendMessage(carbonChat.adventureManager().processMessageWithPapi(player,
this.carbonChat.language().getString("cannot-set-color"),
"br", "\n", "input", color.asHexString(),
"channel", channel.name()));
return;
}
final UserChannelSettings settings = user.channelSettings(channel);
settings.color(color);
user.sendMessage(carbonChat.adventureManager().processMessageWithPapi(player,
this.carbonChat.language().getString("channel-color-set"),
"br", "\n", "color", "<color:" + color.asHexString() + ">", "channel",
channel.name(), "hex", color.asHexString()));
})
.register();
}
}
}
@@ -19,58 +19,58 @@ import java.util.LinkedHashMap;
public class ShadowMuteCommand {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public ShadowMuteCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) {
this.carbonChat = carbonChat;
public ShadowMuteCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) {
return;
}
CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>();
arguments.put("player", CarbonUtils.chatUserArgument());
new CommandAPICommand(commandSettings.getName())
.withArguments(arguments)
.withAliases(commandSettings.getAliasesArray())
.withPermission(CommandPermission.fromString("carbonchat.shadowmute"))
.executes(this::execute)
.register();
if (!commandSettings.enabled()) {
return;
}
private void execute(@NonNull CommandSender sender, @NonNull Object @NonNull [] args) {
ChatUser user = (ChatUser) args[0];
Audience audience = carbonChat.getAdventureManager().getAudiences().audience(sender);
CommandUtils.handleDuplicateCommands(commandSettings);
if (user.isShadowMuted()) {
user.setShadowMuted(false);
String format = carbonChat.getLanguage().getString("no-longer-shadow-muted");
final LinkedHashMap<String, Argument> arguments = new LinkedHashMap<>();
arguments.put("player", CarbonUtils.chatUserArgument());
Component message = carbonChat.getAdventureManager().processMessage(format, "br", "\n",
"player", user.asOfflinePlayer().getName());
new CommandAPICommand(commandSettings.name())
.withArguments(arguments)
.withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.shadowmute"))
.executes(this::execute)
.register();
}
audience.sendMessage(message);
private void execute(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
final ChatUser user = (ChatUser) args[0];
final Audience audience = this.carbonChat.adventureManager().audiences().audience(sender);
if (user.shadowMuted()) {
user.shadowMuted(false);
final String format = this.carbonChat.language().getString("no-longer-shadow-muted");
final Component message = this.carbonChat.adventureManager().processMessage(format, "br", "\n",
"player", user.offlinePlayer().getName());
audience.sendMessage(message);
} else {
Bukkit.getScheduler().runTaskAsynchronously(this.carbonChat, () -> {
final Permission permission = this.carbonChat.permission();
final String format;
if (permission.playerHas(null, user.offlinePlayer(), "carbonchat.shadowmute.exempt")) {
format = this.carbonChat.language().getString("shadow-mute-exempt");
} else {
Bukkit.getScheduler().runTaskAsynchronously(carbonChat, () -> {
Permission permission = carbonChat.getPermission();
String format;
if (permission.playerHas(null, user.asOfflinePlayer(), "carbonchat.shadowmute.exempt")) {
format = carbonChat.getLanguage().getString("shadow-mute-exempt");
} else {
user.setShadowMuted(true);
format = carbonChat.getLanguage().getString("is-now-shadow-muted");
}
Component message = carbonChat.getAdventureManager().processMessage(format, "br", "\n",
"player", user.asOfflinePlayer().getName());
audience.sendMessage(message);
});
user.shadowMuted(true);
format = this.carbonChat.language().getString("is-now-shadow-muted");
}
final Component message = this.carbonChat.adventureManager().processMessage(format, "br", "\n",
"player", user.offlinePlayer().getName());
audience.sendMessage(message);
});
}
}
}
@@ -19,112 +19,112 @@ import java.util.LinkedHashMap;
public class SpyChannelCommand {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public SpyChannelCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) {
this.carbonChat = carbonChat;
public SpyChannelCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) {
return;
}
CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>();
channelArguments.put("channel", CarbonUtils.channelArgument());
new CommandAPICommand(commandSettings.getName())
.withArguments(channelArguments)
.withAliases(commandSettings.getAliasesArray())
.withPermission(CommandPermission.fromString("carbonchat.spy"))
.executesPlayer(this::execute)
.register();
LinkedHashMap<String, Argument> whisperArguments = new LinkedHashMap<>();
whisperArguments.put("channel", new LiteralArgument("whispers"));
new CommandAPICommand(commandSettings.getName())
.withArguments(whisperArguments)
.withAliases(commandSettings.getAliasesArray())
.withPermission(CommandPermission.fromString("carbonchat.spy"))
.executesPlayer(this::executeWhispers)
.register();
LinkedHashMap<String, Argument> everythingArguments = new LinkedHashMap<>();
everythingArguments.put("channel", new LiteralArgument("*"));
everythingArguments.put("should-spy", new BooleanArgument());
new CommandAPICommand(commandSettings.getName())
.withArguments(everythingArguments)
.withAliases(commandSettings.getAliasesArray())
.withPermission(CommandPermission.fromString("carbonchat.spy"))
.executesPlayer(this::executeEverything) // lul
.register();
if (!commandSettings.enabled()) {
return;
}
private void execute(@NonNull Player player, @NonNull Object @NonNull [] args) {
ChatChannel chatChannel = (ChatChannel) args[0];
ChatUser user = carbonChat.getUserService().wrap(player);
CommandUtils.handleDuplicateCommands(commandSettings);
String message;
final LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>();
channelArguments.put("channel", CarbonUtils.channelArgument());
UserChannelSettings settings = user.getChannelSettings(chatChannel);
new CommandAPICommand(commandSettings.name())
.withArguments(channelArguments)
.withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.spy"))
.executesPlayer(this::execute)
.register();
if (settings.isSpying()) {
settings.setSpying(false);
message = carbonChat.getLanguage().getString("spy-toggled-off");
} else {
settings.setSpying(true);
message = carbonChat.getLanguage().getString("spy-toggled-on");
}
final LinkedHashMap<String, Argument> whisperArguments = new LinkedHashMap<>();
whisperArguments.put("channel", new LiteralArgument("whispers"));
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, message, "br", "\n",
"color", "<color:" + chatChannel.getChannelColor(user).toString() + ">", "channel", chatChannel.getName()));
new CommandAPICommand(commandSettings.name())
.withArguments(whisperArguments)
.withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.spy"))
.executesPlayer(this::executeWhispers)
.register();
final LinkedHashMap<String, Argument> everythingArguments = new LinkedHashMap<>();
everythingArguments.put("channel", new LiteralArgument("*"));
everythingArguments.put("should-spy", new BooleanArgument());
new CommandAPICommand(commandSettings.name())
.withArguments(everythingArguments)
.withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.spy"))
.executesPlayer(this::executeEverything) // lul
.register();
}
private void execute(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final ChatChannel chatChannel = (ChatChannel) args[0];
final ChatUser user = this.carbonChat.userService().wrap(player);
final String message;
final UserChannelSettings settings = user.channelSettings(chatChannel);
if (settings.spying()) {
settings.spying(false);
message = this.carbonChat.language().getString("spy-toggled-off");
} else {
settings.spying(true);
message = this.carbonChat.language().getString("spy-toggled-on");
}
private void executeWhispers(@NonNull Player player, @NonNull Object @NonNull [] args) {
ChatUser user = carbonChat.getUserService().wrap(player);
user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, message, "br", "\n",
"color", "<color:" + chatChannel.channelColor(user).toString() + ">", "channel", chatChannel.name()));
}
String message;
private void executeWhispers(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final ChatUser user = this.carbonChat.userService().wrap(player);
if (user.isSpyingWhispers()) {
user.setSpyingWhispers(false);
message = carbonChat.getLanguage().getString("spy-whispers-off");
} else {
user.setSpyingWhispers(true);
message = carbonChat.getLanguage().getString("spy-whispers-on");
}
final String message;
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, message, "br", "\n"));
if (user.spyingwhispers()) {
user.spyingWhispers(false);
message = this.carbonChat.language().getString("spy-whispers-off");
} else {
user.spyingWhispers(true);
message = this.carbonChat.language().getString("spy-whispers-on");
}
private void executeEverything(@NonNull Player player, @NonNull Object @NonNull [] args) {
Boolean shouldSpy = (Boolean) args[0];
user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, message, "br", "\n"));
}
ChatUser user = carbonChat.getUserService().wrap(player);
private void executeEverything(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final Boolean shouldSpy = (Boolean) args[0];
String message;
final ChatUser user = this.carbonChat.userService().wrap(player);
if (shouldSpy) {
user.setSpyingWhispers(true);
final String message;
for (ChatChannel channel : carbonChat.getChannelManager().getRegistry().values()) {
user.getChannelSettings(channel).setSpying(true);
}
if (shouldSpy) {
user.spyingWhispers(true);
message = carbonChat.getLanguage().getString("spy-everything-off");
} else {
user.setSpyingWhispers(false);
for (final ChatChannel channel : this.carbonChat.channelManager().registry().values()) {
user.channelSettings(channel).spying(true);
}
for (ChatChannel channel : carbonChat.getChannelManager().getRegistry().values()) {
user.getChannelSettings(channel).setSpying(false);
}
message = this.carbonChat.language().getString("spy-everything-off");
} else {
user.spyingWhispers(false);
message = carbonChat.getLanguage().getString("spy-everything-on");
}
for (final ChatChannel channel : this.carbonChat.channelManager().registry().values()) {
user.channelSettings(channel).spying(false);
}
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, message, "br", "\n"));
message = this.carbonChat.language().getString("spy-everything-on");
}
user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, message, "br", "\n"));
}
}
@@ -18,60 +18,66 @@ import java.util.LinkedHashMap;
public class SudoChannelCommand {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public SudoChannelCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) {
this.carbonChat = carbonChat;
public SudoChannelCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) {
return;
}
CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> setOtherChannelArguments = new LinkedHashMap<>();
setOtherChannelArguments.put("player", CarbonUtils.onlineChatUserArgument());
setOtherChannelArguments.put("channel", CarbonUtils.channelArgument());
new CommandAPICommand(commandSettings.getName())
.withArguments(setOtherChannelArguments)
.withAliases(commandSettings.getAliasesArray())
.withPermission(CommandPermission.fromString("carbonchat.channel.others"))
.executes((sender, args) -> { this.setOtherChannel(sender, (ChatUser) args[0], (ChatChannel) args[1]); })
.register();
LinkedHashMap<String, Argument> sendMessageOtherArguments = new LinkedHashMap<>();
sendMessageOtherArguments.put("player", CarbonUtils.onlineChatUserArgument());
sendMessageOtherArguments.put("channel", CarbonUtils.channelArgument());
sendMessageOtherArguments.put("message", new GreedyStringArgument());
new CommandAPICommand(commandSettings.getName())
.withArguments(sendMessageOtherArguments)
.withAliases(commandSettings.getAliasesArray())
.withPermission(CommandPermission.fromString("carbonchat.channel.others.message"))
.executes((sender, args) -> { this.sendMessageOther(sender, (ChatUser) args[0], (ChatChannel) args[1], (String) args[2]); })
.register();
if (!commandSettings.enabled()) {
return;
}
private void setOtherChannel(@NonNull CommandSender sender, @NonNull ChatUser user, @NonNull ChatChannel channel) {
user.setSelectedChannel(channel);
CommandUtils.handleDuplicateCommands(commandSettings);
String message = channel.getSwitchMessage();
String otherMessage = channel.getSwitchOtherMessage();
final LinkedHashMap<String, Argument> setOtherChannelArguments = new LinkedHashMap<>();
setOtherChannelArguments.put("player", CarbonUtils.onlineChatUserArgument());
setOtherChannelArguments.put("channel", CarbonUtils.channelArgument());
user.sendMessage(carbonChat.getAdventureManager().processMessage(message, "br", "\n",
"color", "<color:" + channel.getChannelColor(user).toString() + ">", "channel", channel.getName()));
new CommandAPICommand(commandSettings.name())
.withArguments(setOtherChannelArguments)
.withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.channel.others"))
.executes((sender, args) -> {
this.otherChannel(sender, (ChatUser) args[0], (ChatChannel) args[1]);
})
.register();
carbonChat.getAdventureManager().getAudiences().audience(sender).sendMessage(carbonChat.getAdventureManager().processMessage(otherMessage, "br", "\n",
"color", "<color:" + channel.getChannelColor(user).toString() + ">", "channel", channel.getName(),
"player", user.asOfflinePlayer().getName()));
}
final LinkedHashMap<String, Argument> sendMessageOtherArguments = new LinkedHashMap<>();
sendMessageOtherArguments.put("player", CarbonUtils.onlineChatUserArgument());
sendMessageOtherArguments.put("channel", CarbonUtils.channelArgument());
sendMessageOtherArguments.put("message", new GreedyStringArgument());
private void sendMessageOther(@NonNull CommandSender sender, @NonNull ChatUser user, @NonNull ChatChannel channel, @NonNull String message) {
Component component = channel.sendMessage(user, message, false);
new CommandAPICommand(commandSettings.name())
.withArguments(sendMessageOtherArguments)
.withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.channel.others.message"))
.executes((sender, args) -> {
this.sendMessageOther(sender, (ChatUser) args[0], (ChatChannel) args[1], (String) args[2]);
})
.register();
}
carbonChat.getAdventureManager().getAudiences().console().sendMessage(component);
}
private void otherChannel(@NonNull final CommandSender sender, @NonNull final ChatUser user, @NonNull final ChatChannel channel) {
user.selectedChannel(channel);
final String message = channel.switchMessage();
final String otherMessage = channel.switchOtherMessage();
user.sendMessage(this.carbonChat.adventureManager().processMessage(message, "br", "\n",
"color", "<color:" + channel.channelColor(user).toString() + ">", "channel", channel.name()));
this.carbonChat.adventureManager().audiences().audience(sender).sendMessage(
this.carbonChat.adventureManager().processMessage(otherMessage, "br", "\n",
"color", "<color:" + channel.channelColor(user).toString() + ">", "channel", channel.name(),
"player", user.offlinePlayer().getName()));
}
private void sendMessageOther(@NonNull final CommandSender sender, @NonNull final ChatUser user,
@NonNull final ChatChannel channel, @NonNull final String message) {
final Component component = channel.sendMessage(user, message, false);
this.carbonChat.adventureManager().audiences().console().sendMessage(component);
}
}
@@ -18,86 +18,87 @@ import java.util.LinkedHashMap;
public class ToggleCommand {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public ToggleCommand(@NonNull CarbonChat carbonChat, @NonNull CommandSettings commandSettings) {
this.carbonChat = carbonChat;
public ToggleCommand(@NonNull final CarbonChat carbonChat, @NonNull final CommandSettings commandSettings) {
this.carbonChat = carbonChat;
if (!commandSettings.isEnabled()) {
return;
}
CommandUtils.handleDuplicateCommands(commandSettings);
LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>();
channelArguments.put("channel", CarbonUtils.channelArgument());
new CommandAPICommand(commandSettings.getName())
.withArguments(channelArguments)
.withAliases(commandSettings.getAliasesArray())
.withPermission(CommandPermission.fromString("carbonchat.toggle"))
.executesPlayer(this::executeSelf)
.register();
LinkedHashMap<String, Argument> argumentsOther = new LinkedHashMap<>();
argumentsOther.put("players", CarbonUtils.chatUserArgument());
argumentsOther.put("channel", CarbonUtils.channelArgument());
new CommandAPICommand(commandSettings.getName())
.withArguments(argumentsOther)
.withAliases(commandSettings.getAliasesArray())
.withPermission(CommandPermission.fromString("carbonchat.toggle"))
.executes(this::executeOther)
.register();
if (!commandSettings.enabled()) {
return;
}
private void executeSelf(@NonNull Player player, @NonNull Object @NonNull [] args) {
ChatUser user = carbonChat.getUserService().wrap(player);
ChatChannel channel = (ChatChannel) args[0];
CommandUtils.handleDuplicateCommands(commandSettings);
String message;
final LinkedHashMap<String, Argument> channelArguments = new LinkedHashMap<>();
channelArguments.put("channel", CarbonUtils.channelArgument());
UserChannelSettings settings = user.getChannelSettings(channel);
new CommandAPICommand(commandSettings.name())
.withArguments(channelArguments)
.withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.toggle"))
.executesPlayer(this::executeSelf)
.register();
if (!channel.isIgnorable()) {
message = channel.getCannotIgnoreMessage();
} else if (settings.isIgnored()) {
settings.setIgnoring(false);
message = channel.getToggleOffMessage();
} else {
settings.setIgnoring(true);
message = channel.getToggleOnMessage();
}
final LinkedHashMap<String, Argument> argumentsOther = new LinkedHashMap<>();
argumentsOther.put("players", CarbonUtils.chatUserArgument());
argumentsOther.put("channel", CarbonUtils.channelArgument());
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(player, message, "br", "\n",
"color", "<color:" + channel.getChannelColor(user).toString() + ">", "channel", channel.getName()));
new CommandAPICommand(commandSettings.name())
.withArguments(argumentsOther)
.withAliases(commandSettings.aliases())
.withPermission(CommandPermission.fromString("carbonchat.toggle"))
.executes(this::executeOther)
.register();
}
private void executeSelf(@NonNull final Player player, @NonNull final Object @NonNull [] args) {
final ChatUser user = this.carbonChat.userService().wrap(player);
final ChatChannel channel = (ChatChannel) args[0];
final String message;
final UserChannelSettings settings = user.channelSettings(channel);
if (!channel.ignorable()) {
message = channel.cannotIgnoreMessage();
} else if (settings.ignored()) {
settings.ignoring(false);
message = channel.toggleOffMessage();
} else {
settings.ignoring(true);
message = channel.toggleOnMessage();
}
private void executeOther(@NonNull CommandSender sender, @NonNull Object @NonNull [] args) {
ChatUser user = (ChatUser) args[0];
ChatChannel channel = (ChatChannel) args[1];
user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(player, message, "br", "\n",
"color", "<color:" + channel.channelColor(user).toString() + ">", "channel", channel.name()));
}
String message;
String otherMessage;
private void executeOther(@NonNull final CommandSender sender, @NonNull final Object @NonNull [] args) {
final ChatUser user = (ChatUser) args[0];
final ChatChannel channel = (ChatChannel) args[1];
UserChannelSettings settings = user.getChannelSettings(channel);
final String message;
final String otherMessage;
if (settings.isIgnored()) {
settings.setIgnoring(false);
message = channel.getToggleOffMessage();
otherMessage = channel.getToggleOtherOffMessage();
} else {
settings.setIgnoring(true);
message = channel.getToggleOnMessage();
otherMessage = channel.getToggleOtherOnMessage();
}
final UserChannelSettings settings = user.channelSettings(channel);
user.sendMessage(carbonChat.getAdventureManager().processMessage(message, "br", "\n",
"color", "<color:" + channel.getChannelColor(user).toString() + ">", "channel", channel.getName()));
carbonChat.getAdventureManager().getAudiences().audience(sender).sendMessage(carbonChat.getAdventureManager().processMessage(otherMessage,
"br", "\n", "color", "<color:" + channel.getChannelColor(user).toString() + ">",
"channel", channel.getName(), "player", user.asOfflinePlayer().getName()));
if (settings.ignored()) {
settings.ignoring(false);
message = channel.toggleOffMessage();
otherMessage = channel.toggleOtherOffMessage();
} else {
settings.ignoring(true);
message = channel.toggleOnMessage();
otherMessage = channel.toggleOtherOnMessage();
}
user.sendMessage(this.carbonChat.adventureManager().processMessage(message, "br", "\n",
"color", "<color:" + channel.channelColor(user).toString() + ">", "channel", channel.name()));
this.carbonChat.adventureManager().audiences().audience(sender).sendMessage(
this.carbonChat.adventureManager().processMessage(otherMessage,
"br", "\n", "color", "<color:" + channel.channelColor(user).toString() + ">",
"channel", channel.name(), "player", user.offlinePlayer().getName()));
}
}
@@ -11,45 +11,46 @@ import java.util.List;
public class ChannelRegisterEvent extends Event {
/**
* Bukkit event stuff
*/
@NonNull
private static final HandlerList handlers = new HandlerList();
/**
* Bukkit event stuff
*/
@NonNull
private static final HandlerList handlers = new HandlerList();
@Override
@NonNull
public HandlerList getHandlers() {
return handlers;
}
@Override
@NonNull
public HandlerList getHandlers() {
return handlers;
}
@NonNull
public static HandlerList getHandlerList() {
return handlers;
}
@NonNull
@SuppressWarnings("checkstyle:MethodName")
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Relevant stuff
*/
@NonNull
private final List<@NonNull ChatChannel> registeredChannels;
/**
* Relevant stuff
*/
@NonNull
private final List<@NonNull ChatChannel> registeredChannels;
@NonNull
private final Registry<ChatChannel> registry;
@NonNull
private final Registry<ChatChannel> registry;
public ChannelRegisterEvent(@NonNull List<@NonNull ChatChannel> registeredChannels, @NonNull Registry<ChatChannel> registry) {
super(!Bukkit.isPrimaryThread());
public ChannelRegisterEvent(@NonNull final List<@NonNull ChatChannel> registeredChannels, @NonNull final Registry<ChatChannel> registry) {
super(!Bukkit.isPrimaryThread());
this.registeredChannels = registeredChannels;
this.registry = registry;
}
this.registeredChannels = registeredChannels;
this.registry = registry;
}
public void register(@NonNull ChatChannel chatChannel) {
registry.register(chatChannel.getKey(), chatChannel);
}
public void register(@NonNull final ChatChannel chatChannel) {
this.registry.register(chatChannel.key(), chatChannel);
}
@NonNull
public List<@NonNull ChatChannel> getRegisteredChannels() {
return registeredChannels;
}
@NonNull
public List<@NonNull ChatChannel> registeredChannels() {
return this.registeredChannels;
}
}
@@ -11,70 +11,71 @@ import org.checkerframework.checker.nullness.qual.Nullable;
public class ChannelSwitchEvent extends Event implements Cancellable {
/**
* Bukkit event stuff
*/
@NonNull
private static final HandlerList handlers = new HandlerList();
private boolean cancelled = false;
/**
* Bukkit event stuff
*/
@NonNull
private static final HandlerList handlers = new HandlerList();
private boolean cancelled = false;
@Override
@NonNull
public HandlerList getHandlers() {
return handlers;
}
@Override
@NonNull
public HandlerList getHandlers() {
return handlers;
}
@NonNull
public static HandlerList getHandlerList() {
return handlers;
}
@NonNull
@SuppressWarnings("checkstyle:MethodName")
public static HandlerList getHandlerList() {
return handlers;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public void setCancelled(final boolean cancelled) {
this.cancelled = cancelled;
}
/**
* Relevant stuff
*/
@NonNull
private final ChatChannel channel;
/**
* Relevant stuff
*/
@NonNull
private final ChatChannel channel;
@NonNull
private final ChatUser user;
@NonNull
private final ChatUser user;
@Nullable
private String failureMessage;
@Nullable
private String failureMessage;
public ChannelSwitchEvent(@NonNull ChatChannel channel, @NonNull ChatUser user, @Nullable String failureMessage) {
super(!Bukkit.isPrimaryThread());
public ChannelSwitchEvent(@NonNull final ChatChannel channel, @NonNull final ChatUser user, @Nullable final String failureMessage) {
super(!Bukkit.isPrimaryThread());
this.channel = channel;
this.user = user;
this.failureMessage = failureMessage;
}
this.channel = channel;
this.user = user;
this.failureMessage = failureMessage;
}
@NonNull
public ChatUser getUser() {
return user;
}
@NonNull
public ChatUser user() {
return this.user;
}
@NonNull
public ChatChannel getChannel() {
return channel;
}
@NonNull
public ChatChannel channel() {
return this.channel;
}
@Nullable
public String getFailureMessage() {
return failureMessage;
}
@Nullable
public String failureMessage() {
return this.failureMessage;
}
public void setFailureMessage(@Nullable String failureMessage) {
this.failureMessage = failureMessage;
}
public void failureMessage(@Nullable final String failureMessage) {
this.failureMessage = failureMessage;
}
}
@@ -12,87 +12,91 @@ import org.checkerframework.checker.nullness.qual.Nullable;
public class ChatComponentEvent extends Event implements Cancellable {
@NonNull
private static final HandlerList HANDLERS_LIST = new HandlerList();
private boolean isCancelled = false;
@NonNull
private static final HandlerList HANDLERS_LIST = new HandlerList();
private boolean isCancelled = false;
@NonNull
private final ChatUser sender;
@NonNull
private final ChatUser sender;
@Nullable
private final ChatUser target;
@Nullable
private final ChatUser target;
@NonNull
private ChatChannel chatChannel;
@NonNull
private ChatChannel chatChannel;
@NonNull
private TextComponent component;
@NonNull
private TextComponent component;
@NonNull
private final String originalMessage;
@NonNull
private final String originalMessage;
public ChatComponentEvent(@NonNull ChatUser sender, @Nullable ChatUser target, @NonNull ChatChannel chatChannel, @NonNull TextComponent component, @NonNull String originalMessage) {
super(!Bukkit.isPrimaryThread());
public ChatComponentEvent(@NonNull final ChatUser sender, @Nullable final ChatUser target,
@NonNull final ChatChannel chatChannel, @NonNull final TextComponent component,
@NonNull final String originalMessage) {
this.sender = sender;
this.target = target;
this.chatChannel = chatChannel;
this.component = component;
this.originalMessage = originalMessage;
}
super(!Bukkit.isPrimaryThread());
@Override
public boolean isCancelled() {
return isCancelled;
}
this.sender = sender;
this.target = target;
this.chatChannel = chatChannel;
this.component = component;
this.originalMessage = originalMessage;
}
@Override
public void setCancelled(boolean cancelled) {
this.isCancelled = cancelled;
}
@Override
public boolean isCancelled() {
return this.isCancelled;
}
@Override
@NonNull
public HandlerList getHandlers() {
return HANDLERS_LIST;
}
@Override
public void setCancelled(final boolean cancelled) {
this.isCancelled = cancelled;
}
@NonNull
public static HandlerList getHandlerList() {
return HANDLERS_LIST;
}
@Override
@NonNull
public HandlerList getHandlers() {
return HANDLERS_LIST;
}
@NonNull
public ChatUser getSender() {
return sender;
}
@NonNull
@SuppressWarnings("checkstyle:MethodName")
public static HandlerList getHandlerList() {
return HANDLERS_LIST;
}
@Nullable
public ChatUser getTarget() {
return target;
}
@NonNull
public ChatUser sender() {
return this.sender;
}
@NonNull
public ChatChannel getChannel() {
return chatChannel;
}
@Nullable
public ChatUser target() {
return this.target;
}
public void setChannel(@NonNull ChatChannel chatChannel) {
this.chatChannel = chatChannel;
}
@NonNull
public ChatChannel channel() {
return this.chatChannel;
}
@NonNull
public TextComponent getComponent() {
return component;
}
public void channel(@NonNull final ChatChannel chatChannel) {
this.chatChannel = chatChannel;
}
public void setComponent(@NonNull TextComponent component) {
this.component = component;
}
@NonNull
public TextComponent component() {
return this.component;
}
@NonNull
public String getOriginalMessage() {
return originalMessage;
}
public void component(@NonNull final TextComponent component) {
this.component = component;
}
@NonNull
public String originalMessage() {
return this.originalMessage;
}
}
@@ -11,91 +11,94 @@ import org.checkerframework.checker.nullness.qual.Nullable;
public class ChatFormatEvent extends Event implements Cancellable {
@NonNull
private static final HandlerList HANDLERS_LIST = new HandlerList();
private boolean isCancelled = false;
@NonNull
private static final HandlerList HANDLERS_LIST = new HandlerList();
private boolean isCancelled = false;
@NonNull
private final ChatUser sender;
@NonNull
private final ChatUser sender;
@Nullable
private final ChatUser target;
@Nullable
private final ChatUser target;
@NonNull
private ChatChannel chatChannel;
@NonNull
private ChatChannel chatChannel;
@Nullable
private String format;
@Nullable
private String format;
@NonNull
private String message;
@NonNull
private String message;
public ChatFormatEvent(@NonNull ChatUser sender, @Nullable ChatUser target, @NonNull ChatChannel chatChannel, @Nullable String format, @NonNull String message) {
super(!Bukkit.isPrimaryThread());
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());
this.sender = sender;
this.target = target;
this.sender = sender;
this.target = target;
this.chatChannel = chatChannel;
this.format = format;
this.message = message;
}
this.chatChannel = chatChannel;
this.format = format;
this.message = message;
}
@Override
public boolean isCancelled() {
return isCancelled;
}
@Override
public boolean isCancelled() {
return this.isCancelled;
}
@Override
public void setCancelled(boolean cancelled) {
this.isCancelled = cancelled;
}
@Override
public void setCancelled(final boolean cancelled) {
this.isCancelled = cancelled;
}
@Override
@NonNull
public HandlerList getHandlers() {
return HANDLERS_LIST;
}
@Override
@NonNull
public HandlerList getHandlers() {
return HANDLERS_LIST;
}
@NonNull
public static HandlerList getHandlerList() {
return HANDLERS_LIST;
}
@NonNull
@SuppressWarnings("checkstyle:MethodName")
public static HandlerList getHandlerList() {
return HANDLERS_LIST;
}
@NonNull
public ChatUser getSender() {
return sender;
}
@NonNull
public ChatUser sender() {
return this.sender;
}
@Nullable
public ChatUser getTarget() {
return target;
}
@Nullable
public ChatUser target() {
return this.target;
}
@NonNull
public ChatChannel getChannel() {
return chatChannel;
}
@NonNull
public ChatChannel channel() {
return this.chatChannel;
}
public void setChannel(@NonNull ChatChannel chatChannel) {
this.chatChannel = chatChannel;
}
public void channel(@NonNull final ChatChannel chatChannel) {
this.chatChannel = chatChannel;
}
@Nullable
public String getFormat() {
return format;
}
@Nullable
public String format() {
return this.format;
}
public void setFormat(@Nullable String format) {
this.format = format;
}
public void format(@Nullable final String format) {
this.format = format;
}
@NonNull
public String getMessage() {
return message;
}
@NonNull
public String message() {
return this.message;
}
public void setMessage(@NonNull String message) {
this.message = message;
}
public void message(@NonNull final String message) {
this.message = message;
}
}
@@ -11,82 +11,84 @@ import org.checkerframework.checker.nullness.qual.Nullable;
public class PreChatFormatEvent extends Event implements Cancellable {
@NonNull
private static final HandlerList HANDLERS_LIST = new HandlerList();
private boolean isCancelled = false;
@NonNull
private static final HandlerList HANDLERS_LIST = new HandlerList();
private boolean isCancelled = false;
@NonNull
private final ChatUser user;
@NonNull
private final ChatUser user;
@NonNull
private ChatChannel chatChannel;
@NonNull
private ChatChannel chatChannel;
@Nullable
private String format;
@Nullable
private String format;
@NonNull
private String message;
@NonNull
private String message;
public PreChatFormatEvent(@NonNull ChatUser user, @NonNull ChatChannel chatChannel, @Nullable String format, @NonNull String message) {
super(!Bukkit.isPrimaryThread());
public PreChatFormatEvent(@NonNull final ChatUser user, @NonNull final ChatChannel chatChannel,
@Nullable final String format, @NonNull final String message) {
super(!Bukkit.isPrimaryThread());
this.user = user;
this.chatChannel = chatChannel;
this.format = format;
this.message = message;
}
this.user = user;
this.chatChannel = chatChannel;
this.format = format;
this.message = message;
}
@Override
public boolean isCancelled() {
return isCancelled;
}
@Override
public boolean isCancelled() {
return this.isCancelled;
}
@Override
public void setCancelled(boolean cancelled) {
this.isCancelled = cancelled;
}
@Override
public void setCancelled(final boolean cancelled) {
this.isCancelled = cancelled;
}
@Override
@NonNull
public HandlerList getHandlers() {
return HANDLERS_LIST;
}
@Override
@NonNull
public HandlerList getHandlers() {
return HANDLERS_LIST;
}
@NonNull
public static HandlerList getHandlerList() {
return HANDLERS_LIST;
}
@NonNull
@SuppressWarnings("checkstyle:MethodName")
public static HandlerList getHandlerList() {
return HANDLERS_LIST;
}
@NonNull
public ChatUser getUser() {
return user;
}
@NonNull
public ChatUser user() {
return this.user;
}
@NonNull
public ChatChannel getChannel() {
return chatChannel;
}
@NonNull
public ChatChannel channel() {
return this.chatChannel;
}
public void setChannel(@NonNull ChatChannel chatChannel) {
this.chatChannel = chatChannel;
}
public void channel(@NonNull final ChatChannel chatChannel) {
this.chatChannel = chatChannel;
}
@Nullable
public String getFormat() {
return format;
}
@Nullable
public String format() {
return this.format;
}
public void setFormat(@Nullable String format) {
this.format = format;
}
public void format(@Nullable final String format) {
this.format = format;
}
@NonNull
public String getMessage() {
return message;
}
@NonNull
public String message() {
return this.message;
}
public void setMessage(@NonNull String message) {
this.message = message;
}
public void message(@NonNull final String message) {
this.message = message;
}
}
@@ -10,85 +10,89 @@ import org.checkerframework.checker.nullness.qual.NonNull;
public class PrivateMessageEvent extends Event implements Cancellable {
/**
* Bukkit event stuff
*/
@NonNull
private static final HandlerList handlers = new HandlerList();
private boolean cancelled = false;
/**
* Bukkit event stuff
*/
@NonNull
private static final HandlerList handlers = new HandlerList();
private boolean cancelled = false;
@Override
@NonNull
public HandlerList getHandlers() {
return handlers;
}
@Override
@NonNull
public HandlerList getHandlers() {
return handlers;
}
@NonNull
public static HandlerList getHandlerList() {
return handlers;
}
@NonNull
@SuppressWarnings("checkstyle:MethodName")
public static HandlerList getHandlerList() {
return handlers;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public boolean isCancelled() {
return this.cancelled;
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
@Override
public void setCancelled(final boolean cancelled) {
this.cancelled = cancelled;
}
/**
* Relevant stuff
*/
@NonNull
private final ChatUser sender;
/**
* Relevant stuff
*/
@NonNull
private final ChatUser sender;
@NonNull
private final ChatUser target;
@NonNull
private final ChatUser target;
@NonNull
private final Component senderComponent;
@NonNull
private final Component senderComponent;
@NonNull
private final Component targetComponent;
@NonNull
private final Component targetComponent;
@NonNull
private final String message;
@NonNull
private final String message;
public PrivateMessageEvent(@NonNull ChatUser sender, @NonNull ChatUser target, @NonNull Component senderComponent, @NonNull Component targetComponent, @NonNull String message) {
super(!Bukkit.isPrimaryThread());
public PrivateMessageEvent(@NonNull final ChatUser sender, @NonNull final ChatUser target,
@NonNull final Component senderComponent, @NonNull final Component targetComponent,
@NonNull final String message) {
this.sender = sender;
this.target = target;
this.senderComponent = senderComponent;
this.targetComponent = targetComponent;
this.message = message;
}
super(!Bukkit.isPrimaryThread());
@NonNull
public ChatUser getSender() {
return sender;
}
this.sender = sender;
this.target = target;
this.senderComponent = senderComponent;
this.targetComponent = targetComponent;
this.message = message;
}
@NonNull
public ChatUser getTarget() {
return target;
}
@NonNull
public ChatUser sender() {
return this.sender;
}
@NonNull
public Component getSenderComponent() {
return senderComponent;
}
@NonNull
public ChatUser target() {
return this.target;
}
@NonNull
public Component getTargetComponent() {
return targetComponent;
}
@NonNull
public Component senderComponent() {
return this.senderComponent;
}
@NonNull
public String getMessage() {
return message;
}
@NonNull
public Component targetComponent() {
return this.targetComponent;
}
@NonNull
public String message() {
return this.message;
}
}
@@ -14,79 +14,78 @@ import org.checkerframework.checker.nullness.qual.NonNull;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
public class BukkitChatListener implements Listener {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public BukkitChatListener(@NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
public BukkitChatListener(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat;
}
// Chat messages
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerchat(@NonNull final AsyncPlayerChatEvent event) {
final ChatUser user = this.carbonChat.userService().wrap(event.getPlayer());
ChatChannel channel = user.selectedChannel();
if (channel.shouldCancelChatEvent()) {
event.setCancelled(true);
}
// Chat messages
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerchat(AsyncPlayerChatEvent event) {
ChatUser user = carbonChat.getUserService().wrap(event.getPlayer());
ChatChannel channel = user.getSelectedChannel();
for (final ChatChannel entry : this.carbonChat.channelManager().registry().values()) {
if (entry.messagePrefix() == null || entry.messagePrefix().isEmpty()) {
continue;
}
if (channel.shouldCancelChatEvent()) {
event.setCancelled(true);
}
for (ChatChannel entry : carbonChat.getChannelManager().getRegistry().values()) {
if (entry.getMessagePrefix() == null || entry.getMessagePrefix().isEmpty()) {
continue;
}
if (event.getMessage().startsWith(entry.getMessagePrefix())) {
if (entry.canPlayerUse(user)) {
event.setMessage(event.getMessage().substring(entry.getMessagePrefix().length()));
channel = entry;
break;
}
}
}
final ChatChannel selectedChannel = channel;
if (!selectedChannel.canPlayerUse(user)) {
return;
}
final Collection<ChatUser> recipients;
if (selectedChannel.honorsRecipientList()) {
recipients = new HashSet<>();
for (Player recipient : event.getRecipients()) {
recipients.add(carbonChat.getUserService().wrap(recipient));
}
} else {
recipients = (List<ChatUser>) selectedChannel.audiences();
}
event.getRecipients().clear();
if (event.isAsynchronous()) {
Component component = selectedChannel.sendMessage(user, recipients, event.getMessage(), false);
event.setFormat(CarbonChat.LEGACY.serialize(component)
.replaceAll("(?:[^%]|\\A)%(?:[^%]|\\z)", "%%"));
} else {
Bukkit.getScheduler().runTaskAsynchronously(carbonChat, () -> {
Component component = selectedChannel.sendMessage(user, recipients, event.getMessage(), false);
carbonChat.getAdventureManager().getAudiences().console().sendMessage(component);
if (carbonChat.getConfig().getBoolean("show-tips")) {
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");
carbonChat.getLogger().info("Tip: sync chat events and causing this, and let that plugin author know.");
}
});
if (event.getMessage().startsWith(entry.messagePrefix())) {
if (entry.canPlayerUse(user)) {
event.setMessage(event.getMessage().substring(entry.messagePrefix().length()));
channel = entry;
break;
}
}
}
final ChatChannel selectedChannel = channel;
if (!selectedChannel.canPlayerUse(user)) {
return;
}
final Collection<ChatUser> recipients;
if (selectedChannel.honorsRecipientList()) {
recipients = new HashSet<>();
for (final Player recipient : event.getRecipients()) {
recipients.add(this.carbonChat.userService().wrap(recipient));
}
} else {
recipients = selectedChannel.audiences();
}
event.getRecipients().clear();
if (event.isAsynchronous()) {
final Component component = selectedChannel.sendMessage(user, recipients, event.getMessage(), false);
event.setFormat(CarbonChat.LEGACY.serialize(component)
.replaceAll("(?:[^%]|\\A)%(?:[^%]|\\z)", "%%"));
} else {
Bukkit.getScheduler().runTaskAsynchronously(this.carbonChat, () -> {
final Component component = selectedChannel.sendMessage(user, recipients, event.getMessage(), false);
this.carbonChat.adventureManager().audiences().console().sendMessage(component);
if (this.carbonChat.getConfig().getBoolean("show-tips")) {
this.carbonChat.getLogger().info("Tip: Sync chat event! I cannot set the message format due to this. :(");
this.carbonChat.getLogger().info("Tip: To 'solve' this, do a binary search and see which plugin is triggering");
this.carbonChat.getLogger().info("Tip: sync chat events and causing this, and let that plugin author know.");
}
});
}
}
}
@@ -9,42 +9,42 @@ import org.checkerframework.checker.nullness.qual.NonNull;
public class CapsHandler implements Listener {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public CapsHandler(@NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
public CapsHandler(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat;
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onMessage(final PreChatFormatEvent event) {
if (!this.carbonChat.moderationConfig().getBoolean("caps-protection.enabled")) {
return;
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onMessage(PreChatFormatEvent event) {
if (!carbonChat.getModConfig().getBoolean("caps-protection.enabled")) {
return;
}
if (!(event.getMessage().length() >= carbonChat.getModConfig().getInt("caps-protection.minimum-length"))) {
return;
}
int amountOfCaps = 0;
for (char letter : event.getMessage().toCharArray()) {
if (Character.isUpperCase(letter)) {
amountOfCaps++;
}
}
double capsPercentage = (amountOfCaps * 100.0) / event.getMessage().length();
if (!(capsPercentage >= carbonChat.getModConfig().getDouble("caps-protection.percent-caps"))) {
return;
}
if (carbonChat.getModConfig().getBoolean("block-message")) {
event.setCancelled(true);
} else {
event.setMessage(event.getMessage().toLowerCase());
}
if (!(event.message().length() >= this.carbonChat.moderationConfig().getInt("caps-protection.minimum-length"))) {
return;
}
int amountOfCaps = 0;
for (final char letter : event.message().toCharArray()) {
if (Character.isUpperCase(letter)) {
amountOfCaps++;
}
}
final double capsPercentage = (amountOfCaps * 100.0) / event.message().length();
if (!(capsPercentage >= this.carbonChat.moderationConfig().getDouble("caps-protection.percent-caps"))) {
return;
}
if (this.carbonChat.moderationConfig().getBoolean("block-message")) {
event.setCancelled(true);
} else {
event.message(event.message().toLowerCase());
}
}
}
@@ -6,24 +6,25 @@ import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.checkerframework.checker.nullness.qual.NonNull;
public class CustomPlaceholderHandler implements Listener {
private final CarbonChat carbonChat;
private final CarbonChat carbonChat;
public CustomPlaceholderHandler(CarbonChat carbonChat) {
this.carbonChat = carbonChat;
}
public CustomPlaceholderHandler(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat;
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPapiPlaceholder(PreChatFormatEvent event) {
ConfigurationSection placeholders = carbonChat.getConfig().getConfigurationSection("placeholders");
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPapiPlaceholder(final PreChatFormatEvent event) {
final ConfigurationSection placeholders = this.carbonChat.getConfig().getConfigurationSection("placeholders");
for (String key : placeholders.getKeys(false)) {
String value = placeholders.getString(key);
for (final String key : placeholders.getKeys(false)) {
final String value = placeholders.getString(key);
event.setFormat(event.getFormat().replace("<" + key + ">", value));
}
event.format(event.format().replace("<" + key + ">", value));
}
}
}
@@ -19,97 +19,96 @@ import java.util.regex.Pattern;
public class FilterHandler implements Listener {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final Map<String, List<Pattern>> patternReplacements = new HashMap<>();
@NonNull
private final Map<String, List<@NonNull Pattern>> patternReplacements = new HashMap<>();
@NonNull
private final List<Pattern> blockedWords = new ArrayList<>();
@NonNull
private final List<@NonNull Pattern> blockedWords = new ArrayList<>();
public FilterHandler(@NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
reloadFilters();
public FilterHandler(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat;
this.reloadFilters();
}
public void reloadFilters() {
this.patternReplacements.clear();
this.blockedWords.clear();
final FileConfiguration config = this.carbonChat.moderationConfig();
final ConfigurationSection filters = config.getConfigurationSection("filters.filters");
if (filters != null) {
for (final String replacement : filters.getKeys(false)) {
final List<Pattern> patterns = new ArrayList<>();
for (final String word : filters.getStringList(replacement)) {
if (this.carbonChat.moderationConfig().getBoolean("filters.case-sensitive")) {
patterns.add(Pattern.compile(word));
} else {
patterns.add(Pattern.compile(word, Pattern.CASE_INSENSITIVE));
}
}
this.patternReplacements.put(replacement, patterns);
}
}
public void reloadFilters() {
patternReplacements.clear();
blockedWords.clear();
for (final String replacement : config.getStringList("filters.blocked-words")) {
if (this.carbonChat.moderationConfig().getBoolean("filters.case-sensitive")) {
this.blockedWords.add(Pattern.compile(replacement));
} else {
this.blockedWords.add(Pattern.compile(replacement, Pattern.CASE_INSENSITIVE));
}
}
}
FileConfiguration config = carbonChat.getModConfig();
ConfigurationSection filters = config.getConfigurationSection("filters.filters");
if (filters != null) {
for (String replacement : filters.getKeys(false)) {
List<Pattern> patterns = new ArrayList<>();
for (String word : filters.getStringList(replacement)) {
if (carbonChat.getModConfig().getBoolean("filters.case-sensitive")) {
patterns.add(Pattern.compile(word));
} else {
patterns.add(Pattern.compile(word, Pattern.CASE_INSENSITIVE));
}
}
patternReplacements.put(replacement, patterns);
}
}
for (String replacement : config.getStringList("filters.blocked-words")) {
if (carbonChat.getModConfig().getBoolean("filters.case-sensitive")) {
blockedWords.add(Pattern.compile(replacement));
} else {
blockedWords.add(Pattern.compile(replacement, Pattern.CASE_INSENSITIVE));
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onFilter(final PreChatFormatEvent event) {
if (!this.carbonChat.moderationConfig().getBoolean("filters.enabled")) {
return;
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onFilter(PreChatFormatEvent event) {
if (!carbonChat.getModConfig().getBoolean("filters.enabled")) {
return;
}
if (event.getUser().isOnline()) {
if (event.getUser().asPlayer().hasPermission("carbonchat.filter.exempt")) {
return;
}
}
if (!channelUsesFilter(event.getChannel())) {
return;
}
String message = event.getMessage();
//Matcher matcher;
for (Map.Entry<String, List<Pattern>> entry : patternReplacements.entrySet()) {
for (Pattern pattern : entry.getValue()) {
Matcher matcher = pattern.matcher(message);
if (entry.getKey().equals("_")) {
message = matcher.replaceAll("");
} else {
message = matcher.replaceAll(entry.getKey());
}
}
}
event.setMessage(message);
for (Pattern blockedWord : blockedWords) {
if (blockedWord.matcher(event.getMessage()).find()) {
event.setCancelled(true);
break;
}
}
if (event.user().online()) {
if (event.user().player().hasPermission("carbonchat.filter.exempt")) {
return;
}
}
private boolean channelUsesFilter(@NonNull ChatChannel chatChannel) {
Object filter = chatChannel.getContext("filter");
return filter instanceof Boolean && ((Boolean) filter);
if (!this.channelUsesFilter(event.channel())) {
return;
}
String message = event.message();
for (final Map.Entry<String, List<Pattern>> entry : this.patternReplacements.entrySet()) {
for (final Pattern pattern : entry.getValue()) {
final Matcher matcher = pattern.matcher(message);
if (entry.getKey().equals("_")) {
message = matcher.replaceAll("");
} else {
message = matcher.replaceAll(entry.getKey());
}
}
}
event.message(message);
for (final Pattern blockedWord : this.blockedWords) {
if (blockedWord.matcher(event.message()).find()) {
event.setCancelled(true);
break;
}
}
}
private boolean channelUsesFilter(@NonNull final ChatChannel chatChannel) {
final Object filter = chatChannel.context("filter");
return filter instanceof Boolean && ((Boolean) filter);
}
}
@@ -7,15 +7,15 @@ import org.bukkit.event.Listener;
public class IgnoredPlayerHandler implements Listener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPapiPlaceholder(ChatFormatEvent event) {
if (event.getTarget() == null) {
return;
}
if (event.getTarget().isIgnoringUser(event.getSender())) {
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPapiPlaceholder(final ChatFormatEvent event) {
if (event.target() == null) {
return;
}
if (event.target().ignoringUser(event.sender())) {
event.setCancelled(true);
}
}
}
@@ -13,35 +13,35 @@ import java.util.regex.Pattern;
public class ItemLinkHandler implements Listener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onItemLink(ChatComponentEvent event) {
// Handle item linking placeholders
if (event.getSender().isOnline()) {
Player player = event.getSender().asPlayer();
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onItemLink(final ChatComponentEvent event) {
// Handle item linking placeholders
if (event.sender().online()) {
final Player player = event.sender().player();
if (!player.hasPermission("carbonchat.itemlink")) {
return;
}
if (!player.hasPermission("carbonchat.itemlink")) {
return;
}
Component itemComponent = CarbonUtils.createComponent(player);
final Component itemComponent = CarbonUtils.createComponent(player);
if (itemComponent.equals(TextComponent.empty())) {
return;
}
if (itemComponent.equals(TextComponent.empty())) {
return;
}
for (Pattern pattern : event.getChannel().getItemLinkPatterns()) {
String patternContent = pattern.toString().replace("\\Q", "").replace("\\E", "");
for (final Pattern pattern : event.channel().itemLinkPatterns()) {
final String patternContent = pattern.toString().replace("\\Q", "").replace("\\E", "");
if (event.getOriginalMessage().contains(patternContent)) {
TextComponent component = (TextComponent) event.getComponent().replaceFirstText(pattern, (input) -> {
return TextComponent.builder().append(itemComponent);
});
if (event.originalMessage().contains(patternContent)) {
final TextComponent component = (TextComponent) event.component().replaceFirstText(pattern, input -> {
return TextComponent.builder().append(itemComponent);
});
event.setComponent(component);
break;
}
}
event.component(component);
break;
}
}
}
}
}
@@ -10,10 +10,10 @@ import org.bukkit.event.Listener;
public class LegacyFormatHandler implements Listener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onLegacyFormat(PreChatFormatEvent event) {
Component component = CarbonChat.LEGACY.deserialize(event.getFormat());
event.setFormat(MiniMessage.get().serialize(component));
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onLegacyFormat(final PreChatFormatEvent event) {
final Component component = CarbonChat.LEGACY.deserialize(event.format());
event.format(MiniMessage.get().serialize(component));
}
}
@@ -6,11 +6,11 @@ import org.bukkit.event.Listener;
public class MuteHandler implements Listener {
@EventHandler
public void onMute(PreChatFormatEvent event) {
if (event.getUser().isMuted()) {
event.setCancelled(true);
}
@EventHandler
public void onMute(final PreChatFormatEvent event) {
if (event.user().muted()) {
event.setCancelled(true);
}
}
}
@@ -7,12 +7,12 @@ import org.bukkit.event.Listener;
public class OfflineNameHandler implements Listener {
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onOfflineMessage(PreChatFormatEvent event) {
// If the player isn't online (cross server message), use their normal name
if (!event.getUser().isOnline()) {
event.setFormat(event.getFormat().replace("%player_displayname%", "%player_name%"));
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onOfflineMessage(final PreChatFormatEvent event) {
// If the player isn't online (cross server message), use their normal name
if (!event.user().online()) {
event.format(event.format().replace("%player_displayname%", "%player_name%"));
}
}
}
@@ -11,47 +11,47 @@ import org.checkerframework.checker.nullness.qual.NonNull;
public class PingHandler implements Listener {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public PingHandler(@NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
public PingHandler(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPing(final ChatComponentEvent event) {
if (!this.carbonChat.getConfig().getBoolean("pings.enabled")) {
return;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPing(ChatComponentEvent event) {
if (!carbonChat.getConfig().getBoolean("pings.enabled")) {
return;
}
if (event.getTarget() == null) {
return;
}
String targetName = event.getTarget().asOfflinePlayer().getName();
String prefix = carbonChat.getConfig().getString("pings.prefix", "");
boolean caseSensitive = carbonChat.getConfig().getBoolean("pings.case-sensitive", false);
if (targetName == null) {
return;
}
if (caseSensitive) {
if (!event.getOriginalMessage().contains(prefix + targetName)) {
return;
}
} else {
if (!event.getOriginalMessage().toLowerCase().contains((prefix + targetName).toLowerCase())) {
return;
}
}
Key key = Key.of(carbonChat.getConfig().getString("pings.sound"));
Sound.Source source = Sound.Source.valueOf(carbonChat.getConfig().getString("pings.source"));
float volume = (float) carbonChat.getConfig().getDouble("pings.volume");
float pitch = (float) carbonChat.getConfig().getDouble("pings.pitch");
event.getTarget().playSound(Sound.of(key, source, volume, pitch));
if (event.target() == null) {
return;
}
final String targetName = event.target().offlinePlayer().getName();
final String prefix = this.carbonChat.getConfig().getString("pings.prefix", "");
final boolean caseSensitive = this.carbonChat.getConfig().getBoolean("pings.case-sensitive", false);
if (targetName == null) {
return;
}
if (caseSensitive) {
if (!event.originalMessage().contains(prefix + targetName)) {
return;
}
} else {
if (!event.originalMessage().toLowerCase().contains((prefix + targetName).toLowerCase())) {
return;
}
}
final Key key = Key.of(this.carbonChat.getConfig().getString("pings.sound"));
final Sound.Source source = Sound.Source.valueOf(this.carbonChat.getConfig().getString("pings.source"));
final float volume = (float) this.carbonChat.getConfig().getDouble("pings.volume");
final float pitch = (float) this.carbonChat.getConfig().getDouble("pings.pitch");
event.target().playSound(Sound.of(key, source, volume, pitch));
}
}
@@ -8,9 +8,9 @@ import org.bukkit.event.Listener;
public class PlaceholderHandler implements Listener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPapiPlaceholder(PreChatFormatEvent event) {
event.setFormat(PlaceholderAPI.setPlaceholders(event.getUser().asOfflinePlayer(), event.getFormat()));
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPapiPlaceholder(final PreChatFormatEvent event) {
event.format(PlaceholderAPI.setPlaceholders(event.user().offlinePlayer(), event.format()));
}
}
@@ -11,48 +11,48 @@ import org.checkerframework.checker.nullness.qual.NonNull;
public class PlayerJoinListener implements Listener {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public PlayerJoinListener(@NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
public PlayerJoinListener(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat;
}
@EventHandler
public void onPlayerJoin(final PlayerJoinEvent event) {
final ChatUser user = this.carbonChat.userService().wrap(event.getPlayer());
this.carbonChat.userService().validate(user);
if (user.nickname() != null) {
user.nickname(user.nickname());
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
ChatUser user = carbonChat.getUserService().wrap(event.getPlayer());
final String channel = this.carbonChat.getConfig().getString("channel-on-join");
carbonChat.getUserService().validate(user);
if (user.getNickname() != null) {
user.setNickname(user.getNickname());
}
String channel = carbonChat.getConfig().getString("channel-on-join");
if (channel == null || channel.isEmpty()) {
return;
}
if (channel.equals("DEFAULT")) {
user.setSelectedChannel(carbonChat.getChannelManager().getDefaultChannel());
return;
}
ChatChannel chatChannel = carbonChat.getChannelManager().getRegistry().get(channel);
if (chatChannel != null) {
user.setSelectedChannel(chatChannel);
}
if (channel == null || channel.isEmpty()) {
return;
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
ChatUser user = carbonChat.getUserService().wrapIfLoaded(event.getPlayer());
if (user != null) {
carbonChat.getUserService().invalidate(user);
}
if (channel.equals("DEFAULT")) {
user.selectedChannel(this.carbonChat.channelManager().defaultChannel());
return;
}
final ChatChannel chatChannel = this.carbonChat.channelManager().registry().channel(channel);
if (chatChannel != null) {
user.selectedChannel(chatChannel);
}
}
@EventHandler
public void onPlayerQuit(final PlayerQuitEvent event) {
final ChatUser user = this.carbonChat.userService().wrapIfLoaded(event.getPlayer());
if (user != null) {
this.carbonChat.userService().invalidate(user);
}
}
}
@@ -9,20 +9,20 @@ import org.bukkit.event.Listener;
public class RelationalPlaceholderHandler implements Listener {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPapiPlaceholder(ChatFormatEvent event) {
if (event.getTarget() == null) {
return;
}
if (!event.getSender().isOnline() || !event.getTarget().isOnline()) {
return;
}
Player sender = event.getSender().asPlayer();
Player target = event.getTarget().asPlayer();
event.setFormat(PlaceholderAPI.setRelationalPlaceholders(sender, target, event.getFormat()));
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPapiPlaceholder(final ChatFormatEvent event) {
if (event.target() == null) {
return;
}
if (!event.sender().online() || !event.target().online()) {
return;
}
final Player sender = event.sender().player();
final Player target = event.target().player();
event.format(PlaceholderAPI.setRelationalPlaceholders(sender, target, event.format()));
}
}
@@ -10,35 +10,35 @@ import org.checkerframework.checker.nullness.qual.NonNull;
public class ShadowMuteHandler implements Listener {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public ShadowMuteHandler(@NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
public ShadowMuteHandler(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat;
}
@EventHandler(priority = EventPriority.LOWEST)
public void onComponent(final ChatComponentEvent event) {
if (event.sender().shadowMuted()) {
if (!event.sender().equals(event.target())) {
event.setCancelled(true);
}
}
}
@EventHandler
public void on(final ChatFormatEvent event) {
if (event.target() != null) {
return;
}
@EventHandler(priority = EventPriority.LOWEST)
public void onComponent(ChatComponentEvent event) {
if (event.getSender().isShadowMuted()) {
if (!event.getSender().equals(event.getTarget())) {
event.setCancelled(true);
}
}
if (!event.sender().shadowMuted()) {
return;
}
@EventHandler
public void on(ChatFormatEvent event) {
if (event.getTarget() != null) {
return;
}
final String prefix = this.carbonChat.moderationConfig().getString("shadow-mute-prefix", "[SM] ");
if (!event.getSender().isShadowMuted()) {
return;
}
String prefix = carbonChat.getModConfig().getString("shadow-mute-prefix", "[SM] ");
event.setFormat(prefix + event.getFormat());
}
event.format(prefix + event.format());
}
}
@@ -9,26 +9,26 @@ import org.bukkit.event.Listener;
public class UserFormattingHandler implements Listener {
@EventHandler(ignoreCancelled = true)
public void onFormat(PreChatFormatEvent event) {
if (!event.getUser().isOnline()) {
suppressFormatting(event);
return;
}
Player player = event.getUser().asPlayer();
if (!player.hasPermission("carbonchat.formatting") &&
!player.hasPermission("carbonchat.channels." + event.getChannel().getKey() + ".formatting")) {
suppressFormatting(event);
} else {
// Swap the &-style codes for minimessage-compatible strings
event.setMessage(MiniMessage.get().serialize(CarbonChat.LEGACY.deserialize(event.getMessage())));
}
@EventHandler(ignoreCancelled = true)
public void onFormat(final PreChatFormatEvent event) {
if (!event.user().online()) {
this.suppressFormatting(event);
return;
}
private void suppressFormatting(PreChatFormatEvent event) {
event.setFormat(event.getFormat().replace("<message>", "<pre><message></pre>"));
final Player player = event.user().player();
if (!player.hasPermission("carbonchat.formatting") &&
!player.hasPermission("carbonchat.channels." + event.channel().key() + ".formatting")) {
this.suppressFormatting(event);
} else {
// Swap the &-style codes for minimessage-compatible strings
event.message(MiniMessage.get().serialize(CarbonChat.LEGACY.deserialize(event.message())));
}
}
private void suppressFormatting(final PreChatFormatEvent event) {
event.format(event.format().replace("<message>", "<pre><message></pre>"));
}
}
@@ -11,35 +11,35 @@ import org.checkerframework.checker.nullness.qual.NonNull;
public class WhisperPingHandler implements Listener {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public WhisperPingHandler(@NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
public WhisperPingHandler(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPing(final PrivateMessageEvent event) {
if (event.sender().uuid().equals(event.target().uuid())) {
return;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPing(PrivateMessageEvent event) {
if (event.getSender().getUUID().equals(event.getTarget().getUUID())) {
return;
}
final String senderName = event.sender().offlinePlayer().getName();
String senderName = event.getSender().asOfflinePlayer().getName();
if (senderName == null || !event.getMessage().contains(senderName)) {
return;
}
if (!carbonChat.getConfig().getBoolean("whisper.pings.enabled")) {
return;
}
Key key = Key.of(carbonChat.getConfig().getString("whisper.pings.sound"));
Sound.Source source = Sound.Source.valueOf(carbonChat.getConfig().getString("whisper.pings.source"));
float volume = (float) carbonChat.getConfig().getDouble("whisper.pings.volume");
float pitch = (float) carbonChat.getConfig().getDouble("whisper.pings.pitch");
event.getSender().playSound(Sound.of(key, source, volume, pitch));
if (senderName == null || !event.message().contains(senderName)) {
return;
}
if (!this.carbonChat.getConfig().getBoolean("whisper.pings.enabled")) {
return;
}
final Key key = Key.of(this.carbonChat.getConfig().getString("whisper.pings.sound"));
final Sound.Source source = Sound.Source.valueOf(this.carbonChat.getConfig().getString("whisper.pings.source"));
final float volume = (float) this.carbonChat.getConfig().getDouble("whisper.pings.volume");
final float pitch = (float) this.carbonChat.getConfig().getDouble("whisper.pings.pitch");
event.sender().playSound(Sound.of(key, source, volume, pitch));
}
}
@@ -13,61 +13,62 @@ import org.checkerframework.checker.nullness.qual.Nullable;
public class AdventureManager {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final BukkitAudiences audiences;
@NonNull
private final BukkitAudiences audiences;
public AdventureManager(@NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
this.audiences = BukkitAudiences.create(carbonChat);
public AdventureManager(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat;
this.audiences = BukkitAudiences.create(carbonChat);
}
@NonNull
public Component processMessageWithPapi(@NonNull final Player player, @Nullable final String input,
@NonNull final String @NonNull ... placeholders) {
if (input == null || input.trim().isEmpty()) {
return TextComponent.empty();
}
@NonNull
public Component processMessageWithPapi(@NonNull Player player, @Nullable String input, @NonNull String @NonNull ... placeholders) {
if (input == null || input.trim().isEmpty()) {
return TextComponent.empty();
}
return this.processMessage(PlaceholderAPI.setPlaceholders(player, input), placeholders);
}
return processMessage(PlaceholderAPI.setPlaceholders(player, input), placeholders);
@NonNull
public Component processMessage(@Nullable final String input, @NonNull final String @NonNull ... placeholders) {
if (input == null || input.trim().isEmpty()) {
return TextComponent.empty();
}
@NonNull
public Component processMessage(@Nullable String input, @NonNull String @NonNull ... placeholders) {
if (input == null || input.trim().isEmpty()) {
return TextComponent.empty();
}
switch (this.carbonChat.language().getString("formatting.type", "minimessage").toLowerCase()) {
case "minedown":
return MineDown.parse(input, placeholders);
case "mojang":
case "mojangson":
case "json":
return this.processMojang(input, placeholders);
case "minimessage-markdown":
return MiniMessage.markdown().parse(input, placeholders);
case "minimessage":
default:
return MiniMessage.get().parse(input, placeholders);
}
}
switch (carbonChat.getLanguage().getString("formatting.type", "minimessage").toLowerCase()) {
case "minedown":
return MineDown.parse(input, placeholders);
case "mojang":
case "mojangson":
case "json":
return processMojang(input, placeholders);
case "minimessage-markdown":
return MiniMessage.markdown().parse(input, placeholders);
case "minimessage":
default:
return MiniMessage.get().parse(input, placeholders);
}
@NonNull
private Component processMojang(@NonNull String input, @NonNull final String @NonNull ... placeholders) {
for (int i = 0; i < placeholders.length; i += 2) {
final String placeholder = placeholders[i];
final String replacement = placeholders[i + 1];
input = input.replace("<" + placeholder + ">", replacement);
}
@NonNull
private Component processMojang(@NonNull String input, @NonNull String @NonNull ... placeholders) {
for (int i = 0; i < placeholders.length; i += 2) {
String placeholder = placeholders[i];
String replacement = placeholders[i + 1];
return this.audiences().gsonSerializer().deserialize(input);
}
input = input.replace("<" + placeholder + ">", replacement);
}
return getAudiences().gsonSerializer().deserialize(input);
}
@NonNull
public BukkitAudiences getAudiences() {
return audiences;
}
@NonNull
public BukkitAudiences audiences() {
return this.audiences;
}
}
@@ -16,100 +16,101 @@ import java.util.Collections;
public class ChannelManager {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final ChannelRegistry registry;
@NonNull
private final ChannelRegistry registry;
@Nullable
@MonotonicNonNull
private String defaultChannelKey = null;
@Nullable
@MonotonicNonNull
private String defaultChannelKey = null;
public ChannelManager(CarbonChat carbonChat) {
this.carbonChat = carbonChat;
this.registry = new ChannelRegistry(carbonChat);
public ChannelManager(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat;
this.registry = new ChannelRegistry(carbonChat);
reload();
this.reload();
}
public @Nullable ChatChannel loadChannel(@NonNull final String key, @NonNull final ConfigurationSection section) {
final ChatChannel channel = new CarbonChatChannel(key, this.carbonChat, section);
final String name = section.getString("name");
if (name != null && name.length() > 16) {
this.carbonChat.getLogger().warning("Channel name [" + name + "] too long! Max length: 16.");
this.carbonChat.getLogger().warning("Skipping channel, please check your settings!");
return null;
}
public @Nullable ChatChannel loadChannel(String key, @NonNull ConfigurationSection section) {
ChatChannel channel = new CarbonChatChannel(key, carbonChat, section);
return channel;
}
String name = section.getString("name");
public boolean registerChannel(@NonNull final ChatChannel channel) {
final boolean success = this.registry().register(channel.key(), channel);
if (name != null && name.length() > 16) {
carbonChat.getLogger().warning("Channel name [" + name + "] too long! Max length: 16.");
carbonChat.getLogger().warning("Skipping channel, please check your settings!");
return null;
}
if (success) {
if (channel.isDefault() && this.defaultChannelKey == null) {
this.carbonChat.getLogger().info("Default channel registered: " + channel.name());
this.defaultChannelKey = channel.key();
}
return channel;
Bukkit.getPluginManager().callEvent(new ChannelRegisterEvent(Collections.singletonList(channel), this.registry()));
}
public boolean registerChannel(@NonNull ChatChannel channel) {
boolean success = getRegistry().register(channel.getKey(), channel);
return success;
}
if (success) {
if (channel.isDefault() && defaultChannelKey == null) {
carbonChat.getLogger().info("Default channel registered: " + channel.getName());
defaultChannelKey = channel.getKey();
}
public @NonNull Registry<ChatChannel> registry() {
return this.registry;
}
Bukkit.getPluginManager().callEvent(new ChannelRegisterEvent(Collections.singletonList(channel), getRegistry()));
}
return success;
}
public @NonNull Registry<ChatChannel> getRegistry() {
return registry;
public @Nullable ChatChannel defaultChannel() {
if (this.defaultChannelKey != null) {
return this.registry.channel(this.defaultChannelKey);
}
public @Nullable ChatChannel getDefaultChannel() {
if (defaultChannelKey != null) {
return registry.get(defaultChannelKey);
}
return null;
}
return null;
public @Nullable ChatChannel channelOrDefault(@Nullable final String key) {
if (key == null) {
return this.defaultChannel();
}
public @Nullable ChatChannel getChannelOrDefault(@Nullable String key) {
if (key == null) {
return getDefaultChannel();
}
final ChatChannel channel = this.registry.channel(key);
ChatChannel channel = registry.get(key);
if (channel == null) {
return getDefaultChannel();
}
return channel;
if (channel == null) {
return this.defaultChannel();
}
private void reload() {
registry.clearAll();
return channel;
}
private void reload() {
this.registry.clearAll();
for (String key : carbonChat.getConfig().getConfigurationSection("channels").getKeys(false)) {
ConfigurationSection section = carbonChat.getConfig().getConfigurationSection("channels").getConfigurationSection(key);
for (final String key : this.carbonChat.getConfig().getConfigurationSection("channels").getKeys(false)) {
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 (registerChannel(channel)) {
String prefix = channel.getMessagePrefix();
if (channel != null) {
if (this.registerChannel(channel)) {
String prefix = channel.messagePrefix();
if (prefix != null && !prefix.trim().isEmpty()) {
prefix = ("(" + prefix + ") ");
} else {
prefix = "";
}
if (prefix != null && !prefix.trim().isEmpty()) {
prefix = "(" + prefix + ") ";
} else {
prefix = "";
}
carbonChat.getLogger().info("Registering channel: " + prefix + channel.getName());
}
}
this.carbonChat.getLogger().info("Registering channel: " + prefix + channel.name());
}
}
}
}
}
@@ -1,45 +1,60 @@
package net.draycia.carbon.managers;
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 org.bukkit.configuration.ConfigurationSection;
import org.checkerframework.checker.nullness.qual.NonNull;
public class CommandManager {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public CommandManager(@NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
reloadCommands();
}
public CommandManager(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat;
private void reloadCommands() {
new ChannelCommand(carbonChat, getCommandSettings("channel"));
new ChannelListCommand(carbonChat, getCommandSettings("channellist"));
new ChatReloadCommand(carbonChat, getCommandSettings("chatreload"));
new ClearChatCommand(carbonChat, getCommandSettings("clearchat"));
new IgnoreCommand(carbonChat, getCommandSettings("ignore"));
new MeCommand(carbonChat, getCommandSettings("me"));
new MessageCommand(carbonChat, getCommandSettings("message"));
new MuteCommand(carbonChat, getCommandSettings("mute"));
new NicknameCommand(carbonChat, getCommandSettings("nickname"));
new ReplyCommand(carbonChat, getCommandSettings("reply"));
new SetColorCommand(carbonChat, getCommandSettings("setcolor"));
new ShadowMuteCommand(carbonChat, getCommandSettings("shadowmute"));
new SpyChannelCommand(carbonChat, getCommandSettings("spy"));
new SudoChannelCommand(carbonChat, getCommandSettings("sudochannel"));
new ToggleCommand(carbonChat, getCommandSettings("toggle"));
}
this.reloadCommands();
}
@NonNull
private CommandSettings getCommandSettings(@NonNull String command) {
ConfigurationSection section = carbonChat.getCommandsConfig().getConfigurationSection(command);
private void reloadCommands() {
new ChannelCommand(this.carbonChat, this.commandSettings("channel"));
new ChannelListCommand(this.carbonChat, this.commandSettings("channellist"));
new ChatReloadCommand(this.carbonChat, this.commandSettings("chatreload"));
new ClearChatCommand(this.carbonChat, this.commandSettings("clearchat"));
new IgnoreCommand(this.carbonChat, this.commandSettings("ignore"));
new MeCommand(this.carbonChat, this.commandSettings("me"));
new MessageCommand(this.carbonChat, this.commandSettings("message"));
new MuteCommand(this.carbonChat, this.commandSettings("mute"));
new NicknameCommand(this.carbonChat, this.commandSettings("nickname"));
new ReplyCommand(this.carbonChat, this.commandSettings("reply"));
new SetColorCommand(this.carbonChat, this.commandSettings("setcolor"));
new ShadowMuteCommand(this.carbonChat, this.commandSettings("shadowmute"));
new SpyChannelCommand(this.carbonChat, this.commandSettings("spy"));
new SudoChannelCommand(this.carbonChat, this.commandSettings("sudochannel"));
new ToggleCommand(this.carbonChat, this.commandSettings("toggle"));
}
return new CommandSettings(section.getBoolean("enabled"), section.getString("name"),
section.getStringList("aliases"));
}
@NonNull
private CommandSettings commandSettings(@NonNull final String command) {
final ConfigurationSection section = this.carbonChat.commandsConfig().getConfigurationSection(command);
return new CommandSettings(section.getBoolean("enabled"), section.getString("name"),
section.getStringList("aliases"));
}
}
@@ -12,34 +12,34 @@ import java.util.function.Function;
public class ContextManager {
@NonNull
private final Map<@NonNull String, @NonNull Function<@NonNull MessageContext, @NonNull Boolean>> handlers = new HashMap<>();
@NonNull
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) {
if (this.handlers.containsKey(key)) {
return false;
}
this.handlers.put(key, handler);
return true;
public boolean register(@NonNull final String key, @NonNull final Function<@NonNull MessageContext, @NonNull Boolean> handler) {
if (this.handlers.containsKey(key)) {
return false;
}
public boolean testContext(@NonNull ChatUser user, @NonNull ChatUser target, @NonNull ChatChannel channel) {
for (Map.Entry<String, Function<MessageContext, Boolean>> handler : handlers.entrySet()) {
String key = handler.getKey();
this.handlers.put(key, handler);
return true;
}
Object value = channel.getContext(key);
public boolean testContext(@NonNull final ChatUser user, @NonNull final ChatUser target, @NonNull final ChatChannel channel) {
for (final Map.Entry<String, Function<MessageContext, Boolean>> handler : this.handlers.entrySet()) {
final String key = handler.getKey();
if (value == null) {
continue;
}
final Object value = channel.context(key);
MessageContext context = new SimpleMessageContext(user, target, channel, value);
if (value == null) {
continue;
}
return handler.getValue().apply(context);
}
final MessageContext context = new SimpleMessageContext(user, target, channel, value);
return true;
return handler.getValue().apply(context);
}
return true;
}
}
@@ -17,147 +17,148 @@ import java.util.function.Consumer;
public class MessageManager {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final MessageService messageService;
@NonNull
private final MessageService messageService;
@NonNull
private final GsonComponentSerializer gsonSerializer;
@NonNull
private final GsonComponentSerializer gsonSerializer;
public MessageManager(@NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
this.gsonSerializer = carbonChat.getAdventureManager().getAudiences().gsonSerializer();
public MessageManager(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat;
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) {
messageSystem = "none";
}
switch (messageSystem.toLowerCase()) {
case "bungee":
carbonChat.getLogger().info("Using Bungee Plugin Messaging for message forwarding!");
messageService = new BungeeMessageService(carbonChat);
break;
case "redis":
carbonChat.getLogger().info("Using Redis for message forwarding!");
messageService = new RedisMessageService(carbonChat);
break;
case "none":
messageService = new EmptyMessageService();
break;
default:
carbonChat.getLogger().info("Invalid message service selected! Disabling syncing until next restart!");
messageService = new EmptyMessageService();
break;
}
this.registerDefaultListeners();
if (messageSystem == null) {
messageSystem = "none";
}
private void registerDefaultListeners() {
getMessageService().registerUserMessageListener("nickname", (user, byteArray) -> {
String nickname = byteArray.readUTF();
user.setNickname(nickname, true);
if (user.isOnline()) {
String message = carbonChat.getLanguage().getString("nickname-set");
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(user.asPlayer(),
message, "nickname", nickname));
}
});
getMessageService().registerUserMessageListener("nickname-reset", (user, byteArray) -> {
user.setNickname(null, true);
if (user.isOnline()) {
String message = carbonChat.getLanguage().getString("nickname-reset");
user.sendMessage(carbonChat.getAdventureManager().processMessageWithPapi(user.asPlayer(), message));
}
});
getMessageService().registerUserMessageListener("selected-channel", (user, byteArray) -> {
user.setSelectedChannel(carbonChat.getChannelManager().getRegistry().get(byteArray.readUTF()), true);
});
getMessageService().registerUserMessageListener("spying-whispers", (user, byteArray) -> {
user.setSpyingWhispers(byteArray.readBoolean(), true);
});
getMessageService().registerUserMessageListener("muted", (user, byteArray) -> {
user.setMuted(byteArray.readBoolean(), true);
});
getMessageService().registerUserMessageListener("shadow-muted", (user, byteArray) -> {
user.setShadowMuted(byteArray.readBoolean(), true);
});
getMessageService().registerUserMessageListener("reply-target", (user, byteArray) -> {
user.setReplyTarget(new UUID(byteArray.readLong(), byteArray.readLong()), true);
});
getMessageService().registerUserMessageListener("ignoring-user", (user, byteArray) -> {
user.setIgnoringUser(new UUID(byteArray.readLong(), byteArray.readLong()), byteArray.readBoolean(), true);
});
getMessageService().registerUserMessageListener("ignoring-channel", (user, byteArray) -> {
user.getChannelSettings(carbonChat.getChannelManager().getRegistry().get(byteArray.readUTF()))
.setIgnoring(byteArray.readBoolean(), true);
});
getMessageService().registerUserMessageListener("spying-channel", (user, byteArray) -> {
user.getChannelSettings(carbonChat.getChannelManager().getRegistry().get(byteArray.readUTF()))
.setSpying(byteArray.readBoolean(), true);
});
getMessageService().registerUserMessageListener("channel-color", (user, byteArray) -> {
user.getChannelSettings(carbonChat.getChannelManager().getRegistry().get(byteArray.readUTF()))
.setColor(TextColor.fromHexString(byteArray.readUTF()), true);
});
getMessageService().registerUserMessageListener("channel-color-reset", (user, byteArray) -> {
user.getChannelSettings(carbonChat.getChannelManager().getRegistry().get(byteArray.readUTF()))
.setColor(null, true);
});
getMessageService().registerUUIDMessageListener("channel-component", (uuid, byteArray) -> {
ChatChannel channel = carbonChat.getChannelManager().getRegistry().get(byteArray.readUTF());
ChatUser user = carbonChat.getUserService().wrap(uuid);
if (channel != null) {
Component component = gsonSerializer.deserialize(byteArray.readUTF());
channel.sendComponent(user, component);
carbonChat.getAdventureManager().getAudiences().console().sendMessage(component);
}
});
getMessageService().registerUUIDMessageListener("whisper-component", (uuid, byteArray) -> {
UUID recipient = new UUID(byteArray.readLong(), byteArray.readLong());
ChatUser target = carbonChat.getUserService().wrap(recipient);
String message = byteArray.readUTF();
if (!target.isIgnoringUser(uuid)) {
target.setReplyTarget(uuid);
target.sendMessage(gsonSerializer.deserialize(message));
}
});
switch (messageSystem.toLowerCase()) {
case "bungee":
this.carbonChat.getLogger().info("Using Bungee Plugin Messaging for message forwarding!");
this.messageService = new BungeeMessageService(this.carbonChat);
break;
case "redis":
this.carbonChat.getLogger().info("Using Redis for message forwarding!");
this.messageService = new RedisMessageService(this.carbonChat);
break;
case "none":
this.messageService = new EmptyMessageService();
break;
default:
this.carbonChat.getLogger().info("Invalid message service selected! Disabling syncing until next restart!");
this.messageService = new EmptyMessageService();
break;
}
@NonNull
public MessageService getMessageService() {
return messageService;
}
this.registerDefaultListeners();
}
public void sendMessage(@NonNull String key, @NonNull UUID uuid, @NonNull Consumer<@NonNull ByteArrayDataOutput> consumer) {
getMessageService().sendMessage(key, uuid, consumer);
}
private void registerDefaultListeners() {
this.messageService().registerUserMessageListener("nickname", (user, byteArray) -> {
final String nickname = byteArray.readUTF();
user.nickname(nickname, true);
if (user.online()) {
final String message = this.carbonChat.language().getString("nickname-set");
user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(user.player(),
message, "nickname", nickname));
}
});
this.messageService().registerUserMessageListener("nickname-reset", (user, byteArray) -> {
user.nickname(null, true);
if (user.online()) {
final String message = this.carbonChat.language().getString("nickname-reset");
user.sendMessage(this.carbonChat.adventureManager().processMessageWithPapi(user.player(), message));
}
});
this.messageService().registerUserMessageListener("selected-channel", (user, byteArray) -> {
user.selectedChannel(this.carbonChat.channelManager().registry().channel(byteArray.readUTF()), true);
});
this.messageService().registerUserMessageListener("spying-whispers", (user, byteArray) -> {
user.spyingWhispers(byteArray.readBoolean(), true);
});
this.messageService().registerUserMessageListener("muted", (user, byteArray) -> {
user.muted(byteArray.readBoolean(), true);
});
this.messageService().registerUserMessageListener("shadow-muted", (user, byteArray) -> {
user.shadowMuted(byteArray.readBoolean(), true);
});
this.messageService().registerUserMessageListener("reply-target", (user, byteArray) -> {
user.replyTarget(new UUID(byteArray.readLong(), byteArray.readLong()), true);
});
this.messageService().registerUserMessageListener("ignoring-user", (user, byteArray) -> {
user.ignoringUser(new UUID(byteArray.readLong(), byteArray.readLong()), byteArray.readBoolean(), true);
});
this.messageService().registerUserMessageListener("ignoring-channel", (user, byteArray) -> {
user.channelSettings(this.carbonChat.channelManager().registry().channel(byteArray.readUTF()))
.ignoring(byteArray.readBoolean(), true);
});
this.messageService().registerUserMessageListener("spying-channel", (user, byteArray) -> {
user.channelSettings(this.carbonChat.channelManager().registry().channel(byteArray.readUTF()))
.spying(byteArray.readBoolean(), true);
});
this.messageService().registerUserMessageListener("channel-color", (user, byteArray) -> {
user.channelSettings(this.carbonChat.channelManager().registry().channel(byteArray.readUTF()))
.color(TextColor.fromHexString(byteArray.readUTF()), true);
});
this.messageService().registerUserMessageListener("channel-color-reset", (user, byteArray) -> {
user.channelSettings(this.carbonChat.channelManager().registry().channel(byteArray.readUTF()))
.color(null, true);
});
this.messageService().registerUUIDMessageListener("channel-component", (uuid, byteArray) -> {
final ChatChannel channel = this.carbonChat.channelManager().registry().channel(byteArray.readUTF());
final ChatUser user = this.carbonChat.userService().wrap(uuid);
if (channel != null) {
final Component component = this.gsonSerializer.deserialize(byteArray.readUTF());
channel.sendComponent(user, component);
this.carbonChat.adventureManager().audiences().console().sendMessage(component);
}
});
this.messageService().registerUUIDMessageListener("whisper-component", (uuid, byteArray) -> {
final UUID recipient = new UUID(byteArray.readLong(), byteArray.readLong());
final ChatUser target = this.carbonChat.userService().wrap(recipient);
final String message = byteArray.readUTF();
if (!target.ignoringUser(uuid)) {
target.replyTarget(uuid);
target.sendMessage(this.gsonSerializer.deserialize(message));
}
});
}
@NonNull
public MessageService messageService() {
return this.messageService;
}
public void sendMessage(@NonNull final String key, @NonNull final UUID uuid,
@NonNull final Consumer<@NonNull ByteArrayDataOutput> consumer) {
this.messageService().sendMessage(key, uuid, consumer);
}
}
@@ -11,12 +11,12 @@ import java.util.function.Consumer;
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);
}
@@ -18,98 +18,99 @@ import java.util.function.Consumer;
public class BungeeMessageService implements MessageService {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final BungeeChannelApi api;
@NonNull
private final BungeeChannelApi api;
@NonNull
private final Map<@NonNull String, @NonNull BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput>> userLoadedListeners = new HashMap<>();
@NonNull
private final Map<@NonNull String, @NonNull BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput>> userLoadedListeners = new HashMap<>();
@NonNull
private final Map<@NonNull String, @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput>> userNotLoadedListeners = new HashMap<>();
@NonNull
private final Map<@NonNull String, @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput>> userNotLoadedListeners = new HashMap<>();
@NonNull
private final UUID serverUUID = UUID.randomUUID();
@NonNull
private final UUID serverUUID = UUID.randomUUID();
public BungeeMessageService(@NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
public BungeeMessageService(@NonNull final 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) -> {
try {
ByteArrayDataInput input = ByteStreams.newDataInput(bytes);
this.api.registerForwardListener((String channel, Player player, byte[] bytes) -> {
try {
final ByteArrayDataInput input = ByteStreams.newDataInput(bytes);
// Separated out for ease of debugging.
long mostServer = input.readLong();
long leastServer = input.readLong();
// Separated out for ease of debugging.
final long mostServer = input.readLong();
final long leastServer = input.readLong();
UUID messageUUID = new UUID(mostServer, leastServer);
final UUID messageUUID = new UUID(mostServer, leastServer);
if (messageUUID.equals(serverUUID)) {
return;
}
long mostUser = input.readLong();
long leastUser = input.readLong();
UUID userUUID = new UUID(mostUser, leastUser);
this.receiveMessage(userUUID, channel, input);
} catch (IllegalStateException ignored) {}
});
}
private void receiveMessage(@NonNull UUID uuid, @NonNull String key, @NonNull ByteArrayDataInput value) {
ChatUser user = carbonChat.getUserService().wrapIfLoaded(uuid);
if (user != null) {
for (Map.Entry<String, BiConsumer<ChatUser, ByteArrayDataInput>> listener : userLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) {
listener.getValue().accept(user, value);
}
}
if (messageUUID.equals(this.serverUUID)) {
return;
}
for (Map.Entry<String, BiConsumer<UUID, ByteArrayDataInput>> listener : userNotLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) {
listener.getValue().accept(uuid, value);
}
final long mostUser = input.readLong();
final long leastUser = input.readLong();
final UUID userUUID = new UUID(mostUser, leastUser);
this.receiveMessage(userUUID, channel, input);
} catch (final IllegalStateException ignored) {
}
});
}
private void receiveMessage(@NonNull final UUID uuid, @NonNull final String key, @NonNull final ByteArrayDataInput value) {
final ChatUser user = this.carbonChat.userService().wrapIfLoaded(uuid);
if (user != null) {
for (final Map.Entry<String, BiConsumer<ChatUser, ByteArrayDataInput>> listener : this.userLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) {
listener.getValue().accept(user, value);
}
}
}
@Override
public void registerUserMessageListener(@NonNull String key, @NonNull BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput> listener) {
userLoadedListeners.put(key, listener);
for (final Map.Entry<String, BiConsumer<UUID, ByteArrayDataInput>> listener : this.userNotLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) {
listener.getValue().accept(uuid, value);
}
}
}
@Override
public void registerUUIDMessageListener(@NonNull String key, @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) {
userNotLoadedListeners.put(key, listener);
}
@Override
public void registerUserMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput> listener) {
this.userLoadedListeners.put(key, listener);
}
@Override
public void unregisterMessageListener(@NonNull String key) {
userLoadedListeners.remove(key);
userNotLoadedListeners.remove(key);
}
@Override
public void registerUUIDMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) {
this.userNotLoadedListeners.put(key, listener);
}
@Override
public void sendMessage(@NonNull String key, @NonNull UUID uuid, @NonNull Consumer<ByteArrayDataOutput> consumer) {
ByteArrayDataOutput msg = ByteStreams.newDataOutput();
@Override
public void unregisterMessageListener(@NonNull final String key) {
this.userLoadedListeners.remove(key);
this.userNotLoadedListeners.remove(key);
}
msg.writeLong(serverUUID.getMostSignificantBits());
msg.writeLong(serverUUID.getLeastSignificantBits());
msg.writeLong(uuid.getMostSignificantBits());
msg.writeLong(uuid.getLeastSignificantBits());
@Override
public void sendMessage(@NonNull final String key, @NonNull final UUID uuid, @NonNull final Consumer<ByteArrayDataOutput> consumer) {
final ByteArrayDataOutput msg = ByteStreams.newDataOutput();
consumer.accept(msg);
msg.writeLong(this.serverUUID.getMostSignificantBits());
msg.writeLong(this.serverUUID.getLeastSignificantBits());
msg.writeLong(uuid.getMostSignificantBits());
msg.writeLong(uuid.getLeastSignificantBits());
api.forward("ALL", key, msg.toByteArray());
}
consumer.accept(msg);
this.api.forward("ALL", key, msg.toByteArray());
}
}
@@ -12,24 +12,24 @@ import java.util.function.Consumer;
public class EmptyMessageService implements MessageService {
@Override
public void registerUserMessageListener(@NonNull String key, @NonNull BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput> listener) {
// do nothing
}
@Override
public void registerUserMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput> listener) {
// do nothing
}
@Override
public void registerUUIDMessageListener(@NonNull String key, @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) {
// do nothing
}
@Override
public void registerUUIDMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) {
// do nothing
}
@Override
public void unregisterMessageListener(@NonNull String key) {
// do nothing
}
@Override
public void unregisterMessageListener(@NonNull final String key) {
// do nothing
}
@Override
public void sendMessage(@NonNull String key, @NonNull UUID uuid, @NonNull Consumer<@NonNull ByteArrayDataOutput> consumer) {
// do nothing
}
@Override
public void sendMessage(@NonNull final String key, @NonNull final UUID uuid, @NonNull final Consumer<@NonNull ByteArrayDataOutput> consumer) {
// do nothing
}
}
@@ -22,112 +22,112 @@ import java.util.function.Consumer;
public class RedisMessageService implements MessageService {
@NonNull
private final Map<@NonNull String, @NonNull BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput>> userLoadedListeners = new HashMap<>();
@NonNull
private final Map<@NonNull String, @NonNull BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput>> userLoadedListeners = new HashMap<>();
@NonNull
private final Map<@NonNull String, @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput>> userNotLoadedListeners = new HashMap<>();
@NonNull
private final Map<@NonNull String, @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput>> userNotLoadedListeners = new HashMap<>();
@NonNull
private final RedisPubSubCommands<@NonNull String, @NonNull String> subscribeSync;
@NonNull
private final RedisPubSubCommands<@NonNull String, @NonNull String> subscribeSync;
@NonNull
private final RedisPubSubCommands<@NonNull String, @NonNull String> publishSync;
@NonNull
private final RedisPubSubCommands<@NonNull String, @NonNull String> publishSync;
@NonNull
private final UUID serverUUID = UUID.randomUUID();
@NonNull
private final UUID serverUUID = UUID.randomUUID();
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public RedisMessageService(@NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
public RedisMessageService(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat;
String host = carbonChat.getConfig().getString("redis.host");
String password = carbonChat.getConfig().getString("redis.password");
int port = carbonChat.getConfig().getInt("redis.port");
int database = carbonChat.getConfig().getInt("redis.database");
final String host = this.carbonChat.getConfig().getString("redis.host");
final String password = this.carbonChat.getConfig().getString("redis.password");
final int port = this.carbonChat.getConfig().getInt("redis.port");
final int database = this.carbonChat.getConfig().getInt("redis.database");
RedisURI.Builder builder = RedisURI.Builder.redis(host, port)
.withDatabase(database);
final RedisURI.Builder builder = RedisURI.Builder.redis(host, port)
.withDatabase(database);
if (password != null) {
builder.withPassword(password.toCharArray());
if (password != null) {
builder.withPassword(password.toCharArray());
}
final RedisClient client = RedisClient.create(builder.build());
final StatefulRedisPubSubConnection<String, String> subscribeConnection = client.connectPubSub();
this.subscribeSync = subscribeConnection.sync();
final StatefulRedisPubSubConnection<String, String> publishConnection = client.connectPubSub();
this.publishSync = publishConnection.sync();
subscribeConnection.addListener((RedisListener) (channel, message) -> {
final ByteArrayDataInput input = ByteStreams.newDataInput(Base64.getDecoder().decode(message));
final UUID messageUUID = new UUID(input.readLong(), input.readLong());
if (messageUUID.equals(this.serverUUID)) {
return;
}
final UUID uuid = new UUID(input.readLong(), input.readLong());
this.receiveMessage(uuid, channel, input);
});
}
private void receiveMessage(@NonNull final UUID uuid, @NonNull final String key, @NonNull final ByteArrayDataInput value) {
final ChatUser user = this.carbonChat.userService().wrapIfLoaded(uuid);
if (user != null) {
for (final Map.Entry<String, BiConsumer<ChatUser, ByteArrayDataInput>> listener : this.userLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) {
listener.getValue().accept(user, value);
}
RedisClient client = RedisClient.create(builder.build());
StatefulRedisPubSubConnection<String, String> subscribeConnection = client.connectPubSub();
this.subscribeSync = subscribeConnection.sync();
StatefulRedisPubSubConnection<String, String> publishConnection = client.connectPubSub();
this.publishSync = publishConnection.sync();
subscribeConnection.addListener((RedisListener) (channel, message) -> {
ByteArrayDataInput input = ByteStreams.newDataInput(Base64.getDecoder().decode(message));
UUID messageUUID = new UUID(input.readLong(), input.readLong());
if (messageUUID.equals(serverUUID)) {
return;
}
UUID uuid = new UUID(input.readLong(), input.readLong());
this.receiveMessage(uuid, channel, input);
});
}
}
private void receiveMessage(@NonNull UUID uuid, @NonNull String key, @NonNull ByteArrayDataInput value) {
ChatUser user = carbonChat.getUserService().wrapIfLoaded(uuid);
if (user != null) {
for (Map.Entry<String, BiConsumer<ChatUser, ByteArrayDataInput>> listener : userLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) {
listener.getValue().accept(user, value);
}
}
}
for (Map.Entry<String, BiConsumer<UUID, ByteArrayDataInput>> listener : userNotLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) {
listener.getValue().accept(uuid, value);
}
}
for (final Map.Entry<String, BiConsumer<UUID, ByteArrayDataInput>> listener : this.userNotLoadedListeners.entrySet()) {
if (key.equals(listener.getKey())) {
listener.getValue().accept(uuid, value);
}
}
}
@Override
public void registerUserMessageListener(@NonNull String key, @NonNull BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput> listener) {
userLoadedListeners.put(key, listener);
subscribeSync.subscribe(key);
}
@Override
public void registerUserMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull ChatUser, @NonNull ByteArrayDataInput> listener) {
this.userLoadedListeners.put(key, listener);
this.subscribeSync.subscribe(key);
}
@Override
public void registerUUIDMessageListener(@NonNull String key, @NonNull BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) {
userNotLoadedListeners.put(key, listener);
subscribeSync.subscribe(key);
}
@Override
public void registerUUIDMessageListener(@NonNull final String key, @NonNull final BiConsumer<@NonNull UUID, @NonNull ByteArrayDataInput> listener) {
this.userNotLoadedListeners.put(key, listener);
this.subscribeSync.subscribe(key);
}
@Override
public void unregisterMessageListener(@NonNull String key) {
userLoadedListeners.remove(key);
userNotLoadedListeners.remove(key);
@Override
public void unregisterMessageListener(@NonNull final String key) {
this.userLoadedListeners.remove(key);
this.userNotLoadedListeners.remove(key);
subscribeSync.unsubscribe(key);
}
this.subscribeSync.unsubscribe(key);
}
@Override
public void sendMessage(@NonNull String key, @NonNull UUID uuid, @NonNull Consumer<@NonNull ByteArrayDataOutput> consumer) {
ByteArrayDataOutput msg = ByteStreams.newDataOutput();
@Override
public void sendMessage(@NonNull final String key, @NonNull final UUID uuid, @NonNull final Consumer<@NonNull ByteArrayDataOutput> consumer) {
final ByteArrayDataOutput msg = ByteStreams.newDataOutput();
msg.writeLong(serverUUID.getMostSignificantBits());
msg.writeLong(serverUUID.getLeastSignificantBits());
msg.writeLong(uuid.getMostSignificantBits());
msg.writeLong(uuid.getLeastSignificantBits());
msg.writeLong(this.serverUUID.getMostSignificantBits());
msg.writeLong(this.serverUUID.getLeastSignificantBits());
msg.writeLong(uuid.getMostSignificantBits());
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()));
}
}
@@ -11,101 +11,101 @@ import java.util.UUID;
public interface ChatUser extends Audience {
@Nullable
Player asPlayer();
@Nullable
Player player();
@NonNull
OfflinePlayer asOfflinePlayer();
@NonNull
OfflinePlayer offlinePlayer();
@NonNull
UUID getUUID();
@NonNull
UUID uuid();
boolean isOnline();
boolean online();
@Nullable
String getNickname();
@Nullable
String nickname();
default void setNickname(@NonNull String nickname) {
this.setNickname(nickname, false);
}
default void nickname(@NonNull final String nickname) {
this.nickname(nickname, false);
}
void setNickname(@Nullable String nickname, boolean fromRemote);
void nickname(@Nullable String nickname, boolean fromRemote);
@Nullable
ChatChannel getSelectedChannel();
@Nullable
ChatChannel selectedChannel();
default void setSelectedChannel(@NonNull ChatChannel channel) {
this.setSelectedChannel(channel, false);
}
default void selectedChannel(@NonNull final ChatChannel channel) {
this.selectedChannel(channel, false);
}
void setSelectedChannel(@NonNull ChatChannel channel, boolean fromRemote);
void selectedChannel(@NonNull ChatChannel channel, boolean fromRemote);
void clearSelectedChannel();
void clearSelectedChannel();
@NonNull
UserChannelSettings getChannelSettings(@NonNull ChatChannel channel);
@NonNull
UserChannelSettings channelSettings(@NonNull ChatChannel channel);
boolean isSpyingWhispers();
boolean spyingwhispers();
default void setSpyingWhispers(boolean spyingWhispers) {
this.setSpyingWhispers(spyingWhispers, false);
}
default void spyingWhispers(final boolean spyingWhispers) {
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) {
this.setMuted(muted, false);
}
default void muted(final boolean muted) {
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) {
this.setShadowMuted(shadowMuted, false);
}
default void shadowMuted(final boolean shadowMuted) {
this.shadowMuted(shadowMuted, false);
}
void setShadowMuted(boolean shadowMuted, boolean fromRemote);
void shadowMuted(boolean shadowMuted, boolean fromRemote);
@Nullable
UUID getReplyTarget();
@Nullable
UUID replyTarget();
default void setReplyTarget(@Nullable UUID target) {
this.setReplyTarget(target, false);
}
default void replyTarget(@Nullable final UUID target) {
this.replyTarget(target, false);
}
default void setReplyTarget(@Nullable ChatUser user) {
this.setReplyTarget(user.getUUID(), false);
}
default void replyTarget(@Nullable final ChatUser user) {
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) {
this.setReplyTarget(user.getUUID(), fromRemote);
}
default void replyTarget(@Nullable final ChatUser user, final boolean 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) {
this.setIgnoringUser(uuid, ignoring, false);
}
default void ignoringUser(@NonNull final UUID uuid, final boolean ignoring) {
this.ignoringUser(uuid, ignoring, false);
}
default boolean isIgnoringUser(@NonNull ChatUser user) {
return this.isIgnoringUser(user.getUUID());
}
default boolean ignoringUser(@NonNull final ChatUser user) {
return this.ignoringUser(user.uuid());
}
default void setIgnoringUser(@NonNull ChatUser user, boolean ignoring, boolean fromRemote) {
this.setIgnoringUser(user.getUUID(), ignoring, fromRemote);
}
default void ignoringUser(@NonNull final ChatUser user, final boolean ignoring, final boolean fromRemote) {
this.ignoringUser(user.uuid(), ignoring, fromRemote);
}
default void setIgnoringUser(@NonNull ChatUser user, boolean ignoring) {
this.setIgnoringUser(user.getUUID(), ignoring, false);
}
default void ignoringUser(@NonNull final ChatUser user, final boolean ignoring) {
this.ignoringUser(user.uuid(), ignoring, false);
}
void sendMessage(@NonNull ChatUser sender, @NonNull String message);
void sendMessage(@NonNull final ChatUser sender, @NonNull String message);
}
@@ -6,35 +6,30 @@ import java.util.List;
public class CommandSettings {
private final boolean enabled;
private final boolean enabled;
@NonNull
private final String name;
@NonNull
private final String name;
@NonNull
private final List<@NonNull String> aliases;
@NonNull
private final List<@NonNull String> aliases;
public CommandSettings(boolean enabled, @NonNull String name, @NonNull List<@NonNull String> aliases) {
this.enabled = enabled;
this.name = name;
this.aliases = aliases;
}
public CommandSettings(final boolean enabled, @NonNull final String name, @NonNull final List<@NonNull String> aliases) {
this.enabled = enabled;
this.name = name;
this.aliases = aliases;
}
public @NonNull String @NonNull [] getAliasesArray() {
return aliases.toArray(new String[0]);
}
public @NonNull String @NonNull [] aliases() {
return this.aliases.toArray(new String[0]);
}
@NonNull
public List<@NonNull String> getAliases() {
return aliases;
}
@NonNull
public String name() {
return this.name;
}
@NonNull
public String getName() {
return name;
}
public boolean isEnabled() {
return enabled;
}
public boolean enabled() {
return this.enabled;
}
}
@@ -5,29 +5,29 @@ import org.checkerframework.checker.nullness.qual.Nullable;
public interface UserChannelSettings {
boolean isSpying();
boolean spying();
default void setSpying(boolean spying) {
this.setSpying(spying, false);
}
default void spying(final boolean spying) {
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) {
this.setIgnoring(ignored, false);
}
default void ignoring(final boolean ignored) {
this.ignoring(ignored, false);
}
@Nullable
TextColor getColor();
@Nullable
TextColor color();
default void setColor(@Nullable TextColor color) {
this.setColor(color, false);
}
default void color(@Nullable final TextColor color) {
this.color(color, false);
}
void setColor(@Nullable TextColor color, boolean fromRemote);
void color(@Nullable TextColor color, boolean fromRemote);
}
@@ -8,30 +8,30 @@ import java.util.UUID;
public interface UserService {
@Nullable
ChatUser wrap(String name);
@Nullable
ChatUser wrap(String name);
@Nullable
ChatUser wrap(OfflinePlayer player);
@Nullable
ChatUser wrap(OfflinePlayer player);
@Nullable
ChatUser wrap(UUID uuid);
@Nullable
ChatUser wrap(UUID uuid);
@Nullable
default ChatUser wrapIfLoaded(@NonNull OfflinePlayer player) {
return wrapIfLoaded(player.getUniqueId());
}
@Nullable
default ChatUser wrapIfLoaded(@NonNull final OfflinePlayer player) {
return this.wrapIfLoaded(player.getUniqueId());
}
@Nullable
ChatUser wrapIfLoaded(@NonNull UUID uuid);
@Nullable
ChatUser wrapIfLoaded(@NonNull UUID uuid);
@Nullable
ChatUser refreshUser(@NonNull UUID uuid);
@Nullable
ChatUser refreshUser(@NonNull UUID uuid);
void onDisable();
void onDisable();
void invalidate(@NonNull ChatUser user);
void invalidate(@NonNull ChatUser user);
void validate(@NonNull ChatUser user);
void validate(@NonNull ChatUser user);
}
@@ -19,364 +19,370 @@ import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.NonNull;
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 {
@NonNull
private final transient CarbonChat carbonChat;
@NonNull
private final Map<@NonNull String, @NonNull SimpleUserChannelSettings> channelSettings = new HashMap<>();
@NonNull
private final List<@NonNull UUID> ignoredUsers = new ArrayList<>();
@MonotonicNonNull // @NonNull but not initialised in all constructors.
private UUID uuid;
@Nullable
private String selectedChannel = null;
private boolean muted = false;
private boolean shadowMuted = false;
private boolean spyingWhispers = false;
@NonNull
private final transient CarbonChat carbonChat;
@NonNull
private final Map<@NonNull String, @NonNull SimpleUserChannelSettings> channelSettings = new HashMap<>();
@NonNull
private final List<@NonNull UUID> ignoredUsers = new ArrayList<>();
@MonotonicNonNull // @NonNull but not initialised in all constructors.
private UUID uuid;
@Nullable
private String selectedChannel = null;
private boolean muted = false;
private boolean shadowMuted = false;
private boolean spyingWhispers = false;
@Nullable
private String nickname = null;
@Nullable
private String nickname = null;
@Nullable
private transient UUID replyTarget = null;
@Nullable
private transient UUID replyTarget = null;
public CarbonChatUser() {
this.carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
public CarbonChatUser() {
this.carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
}
public CarbonChatUser(@NonNull final UUID uuid) {
this();
this.uuid = uuid;
}
@Override
@NonNull
public Iterable<@NonNull ? extends Audience> audiences() {
return Collections.singleton(this.carbonChat.adventureManager().audiences().player(this.uuid));
}
@Override
@Nullable
public Player player() {
return Bukkit.getPlayer(this.uuid);
}
@Override
@NonNull
public OfflinePlayer offlinePlayer() {
return Bukkit.getOfflinePlayer(this.uuid);
}
@Override
public boolean online() {
return this.offlinePlayer().isOnline();
}
@Override
@NonNull
public UUID uuid() {
return this.uuid;
}
@Override
@Nullable
public String nickname() {
return this.nickname;
}
@Override
public void nickname(@Nullable String newNickname, final boolean fromRemote) {
this.nickname = newNickname;
if (this.online()) {
if (newNickname != null) {
final Component component = this.carbonChat.adventureManager().processMessage(this.nickname);
newNickname = this.carbonChat.LEGACY.serialize(component);
}
this.player().setDisplayName(newNickname);
if (this.carbonChat.getConfig().getBoolean("nicknames-set-tab-name")) {
this.player().setPlayerListName(newNickname);
}
}
public CarbonChatUser(@NonNull UUID uuid) {
this();
this.uuid = uuid;
}
@Override
@NonNull
public Iterable<@NonNull ? extends Audience> audiences() {
return Collections.singleton(carbonChat.getAdventureManager().getAudiences().player(uuid));
}
@Override
@Nullable
public Player asPlayer() {
return Bukkit.getPlayer(uuid);
}
@Override
@NonNull
public OfflinePlayer asOfflinePlayer() {
return Bukkit.getOfflinePlayer(uuid);
}
@Override
public boolean isOnline() {
return asOfflinePlayer().isOnline();
}
@Override
@NonNull
public UUID getUUID() {
return uuid;
}
@Override
@Nullable
public String getNickname() {
return nickname;
}
@Override
public void setNickname(@Nullable String newNickname, boolean fromRemote) {
this.nickname = newNickname;
if (isOnline()) {
if (newNickname != null) {
Component component = carbonChat.getAdventureManager().processMessage(nickname);
newNickname = CarbonChat.LEGACY.serialize(component);
}
this.asPlayer().setDisplayName(newNickname);
if (carbonChat.getConfig().getBoolean("nicknames-set-tab-name")) {
this.asPlayer().setPlayerListName(newNickname);
}
}
if (!fromRemote) {
if (nickname == null) {
carbonChat.getMessageManager().sendMessage("nickname-reset", this.getUUID(), (byteArray) -> {});
} else {
carbonChat.getMessageManager().sendMessage("nickname", this.getUUID(), (byteArray) -> {
byteArray.writeUTF(this.nickname);
});
}
}
}
@Override
@Nullable
public ChatChannel getSelectedChannel() {
return carbonChat.getChannelManager().getChannelOrDefault(selectedChannel);
}
@Override
public void setSelectedChannel(@NonNull ChatChannel chatChannel, boolean fromRemote) {
String failureMessage = chatChannel.getSwitchFailureMessage();
ChannelSwitchEvent event = new ChannelSwitchEvent(chatChannel, this, failureMessage);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled()) {
sendMessage(carbonChat.getAdventureManager().processMessage(event.getFailureMessage(),
"channel", chatChannel.getName()));
return;
}
this.selectedChannel = chatChannel.getKey();
if (!fromRemote) {
carbonChat.getMessageManager().sendMessage("selected-channel", this.getUUID(), (byteArray) -> {
byteArray.writeUTF(chatChannel.getKey());
});
}
}
@Override
public void clearSelectedChannel() {
setSelectedChannel(carbonChat.getChannelManager().getDefaultChannel());
}
@Override
public boolean isIgnoringUser(@NonNull UUID uuid) {
return ignoredUsers.contains(uuid);
}
@Override
public void setIgnoringUser(@NonNull UUID uuid, boolean ignoring, boolean fromRemote) {
if (ignoring) {
ignoredUsers.add(uuid);
} else {
ignoredUsers.remove(uuid);
}
if (!fromRemote) {
carbonChat.getMessageManager().sendMessage("ignoring-user", this.getUUID(), (byteArray) -> {
byteArray.writeLong(uuid.getMostSignificantBits());
byteArray.writeLong(uuid.getLeastSignificantBits());
byteArray.writeBoolean(ignoring);
});
}
}
@NonNull
public List<@NonNull UUID> getIgnoredUsers() {
return ignoredUsers;
}
@Override
public void setMuted(boolean muted, boolean fromRemote) {
this.muted = muted;
if (!fromRemote) {
carbonChat.getMessageManager().sendMessage("muted", this.getUUID(), (byteArray) -> {
byteArray.writeBoolean(muted);
});
}
}
@Override
public boolean isMuted() {
return muted;
}
@Override
public void setShadowMuted(boolean shadowMuted, boolean fromRemote) {
this.shadowMuted = shadowMuted;
if (!fromRemote) {
carbonChat.getMessageManager().sendMessage("shadow-muted", this.getUUID(), (byteArray) -> {
byteArray.writeBoolean(shadowMuted);
});
}
}
@Override
public boolean isShadowMuted() {
return shadowMuted;
}
@Override
@Nullable
public UUID getReplyTarget() {
return replyTarget;
}
@Override
public void setReplyTarget(@Nullable UUID target, boolean fromRemote) {
this.replyTarget = target;
if (!fromRemote) {
carbonChat.getMessageManager().sendMessage("reply-target", this.getUUID(), (byteArray) -> {
byteArray.writeLong(target.getMostSignificantBits());
byteArray.writeLong(target.getLeastSignificantBits());
});
}
}
@Override
@NonNull
public UserChannelSettings getChannelSettings(@NonNull ChatChannel channel) {
return channelSettings.computeIfAbsent(channel.getKey(), (name) -> {
return new SimpleUserChannelSettings(uuid, channel.getKey());
if (!fromRemote) {
if (this.nickname == null) {
this.carbonChat.messageManager().sendMessage("nickname-reset", this.uuid(), byteArray -> {
});
} else {
this.carbonChat.messageManager().sendMessage("nickname", this.uuid(), byteArray -> {
byteArray.writeUTF(this.nickname);
});
}
}
}
@Override
@Nullable
public ChatChannel selectedChannel() {
return this.carbonChat.channelManager().channelOrDefault(this.selectedChannel);
}
@Override
public void selectedChannel(@NonNull final ChatChannel chatChannel, final boolean fromRemote) {
final String failureMessage = chatChannel.switchFailureMessage();
final ChannelSwitchEvent event = new ChannelSwitchEvent(chatChannel, this, failureMessage);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled()) {
this.sendMessage(this.carbonChat.adventureManager().processMessage(event.failureMessage(),
"channel", chatChannel.name()));
return;
}
@NonNull
public Map<@NonNull String, @NonNull ? extends UserChannelSettings> getChannelSettings() {
return channelSettings;
this.selectedChannel = chatChannel.key();
if (!fromRemote) {
this.carbonChat.messageManager().sendMessage("selected-channel", this.uuid(), byteArray -> {
byteArray.writeUTF(chatChannel.key());
});
}
}
@Override
public void clearSelectedChannel() {
this.selectedChannel(this.carbonChat.channelManager().defaultChannel());
}
@Override
public boolean ignoringUser(@NonNull final UUID uuid) {
return this.ignoredUsers.contains(uuid);
}
@Override
public void ignoringUser(@NonNull final UUID uuid, final boolean ignoring, final boolean fromRemote) {
if (ignoring) {
this.ignoredUsers.add(uuid);
} else {
this.ignoredUsers.remove(uuid);
}
@Override
public void setSpyingWhispers(boolean spyingWhispers, boolean fromRemote) {
this.spyingWhispers = spyingWhispers;
if (!fromRemote) {
this.carbonChat.messageManager().sendMessage("ignoring-user", this.uuid(), byteArray -> {
byteArray.writeLong(uuid.getMostSignificantBits());
byteArray.writeLong(uuid.getLeastSignificantBits());
byteArray.writeBoolean(ignoring);
});
}
}
if (!fromRemote) {
carbonChat.getMessageManager().sendMessage("spying-whispers", this.getUUID(), (byteArray) -> {
byteArray.writeBoolean(spyingWhispers);
});
}
@NonNull
public List<@NonNull UUID> ignoredUsers() {
return this.ignoredUsers;
}
@Override
public void muted(final boolean muted, final boolean fromRemote) {
this.muted = muted;
if (!fromRemote) {
this.carbonChat.messageManager().sendMessage("muted", this.uuid(), byteArray -> {
byteArray.writeBoolean(muted);
});
}
}
@Override
public boolean muted() {
return this.muted;
}
@Override
public void shadowMuted(final boolean shadowMuted, final boolean fromRemote) {
this.shadowMuted = shadowMuted;
if (!fromRemote) {
this.carbonChat.messageManager().sendMessage("shadow-muted", this.uuid(), byteArray -> {
byteArray.writeBoolean(shadowMuted);
});
}
}
@Override
public boolean shadowMuted() {
return this.shadowMuted;
}
@Override
@Nullable
public UUID replyTarget() {
return this.replyTarget;
}
@Override
public void replyTarget(@Nullable final UUID target, final boolean fromRemote) {
this.replyTarget = target;
if (!fromRemote) {
this.carbonChat.messageManager().sendMessage("reply-target", this.uuid(), byteArray -> {
byteArray.writeLong(target.getMostSignificantBits());
byteArray.writeLong(target.getLeastSignificantBits());
});
}
}
@Override
@NonNull
public UserChannelSettings channelSettings(@NonNull final ChatChannel channel) {
return this.channelSettings.computeIfAbsent(channel.key(), name -> {
return new SimpleUserChannelSettings(this.uuid, channel.key());
});
}
@NonNull
public Map<@NonNull String, @NonNull ? extends UserChannelSettings> channelSettings() {
return this.channelSettings;
}
@Override
public void spyingWhispers(final boolean spyingWhispers, final boolean fromRemote) {
this.spyingWhispers = spyingWhispers;
if (!fromRemote) {
this.carbonChat.messageManager().sendMessage("spying-whispers", this.uuid(), byteArray -> {
byteArray.writeBoolean(spyingWhispers);
});
}
}
@Override
public boolean spyingwhispers() {
return this.spyingWhispers;
}
@Override
public void sendMessage(@NonNull final ChatUser sender, @NonNull final String message) {
if (this.ignoringUser(sender) || sender.ignoringUser(this)) {
return;
}
@Override
public boolean isSpyingWhispers() {
return spyingWhispers;
final String toPlayerFormat = this.carbonChat.language().getString("message-to-other");
final String fromPlayerFormat = this.carbonChat.language().getString("message-from-other");
String senderName = sender.offlinePlayer().getName();
final String senderOfflineName = senderName;
String targetName = this.offlinePlayer().getName();
final String targetOfflineName = targetName;
if (sender.online()) {
senderName = sender.player().getDisplayName();
}
@Override
public void sendMessage(@NonNull ChatUser sender, @NonNull String message) {
if (isIgnoringUser(sender) || sender.isIgnoringUser(this)) {
return;
}
String toPlayerFormat = carbonChat.getLanguage().getString("message-to-other");
String fromPlayerFormat = carbonChat.getLanguage().getString("message-from-other");
String senderName = sender.asOfflinePlayer().getName();
String senderOfflineName = senderName;
String targetName = this.asOfflinePlayer().getName();
String targetOfflineName = targetName;
if (sender.isOnline()) {
senderName = sender.asPlayer().getDisplayName();
}
if (this.isOnline()) {
targetName = this.asPlayer().getDisplayName();
}
Component toPlayerComponent = carbonChat.getAdventureManager().processMessage(toPlayerFormat, "br", "\n",
"message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName,
"target", targetName, "sender", senderName);
Component fromPlayerComponent = carbonChat.getAdventureManager().processMessage(fromPlayerFormat, "br", "\n",
"message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName,
"target", targetName, "sender", senderName);
PrivateMessageEvent event = new PrivateMessageEvent(sender, this, toPlayerComponent, fromPlayerComponent, message);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
if (this.isOnline()) {
if (sender.isOnline()) {
sender.sendMessage(toPlayerComponent);
if (sender.isShadowMuted()) {
return;
}
this.sendMessage(fromPlayerComponent);
sender.setReplyTarget(this);
this.setReplyTarget(sender);
if (carbonChat.getConfig().getBoolean("pings.on-whisper")) {
Key key = Key.of(carbonChat.getConfig().getString("pings.sound"));
Sound.Source source = Sound.Source.valueOf(carbonChat.getConfig().getString("pings.source"));
float volume = (float) carbonChat.getConfig().getDouble("pings.volume");
float pitch = (float) carbonChat.getConfig().getDouble("pings.pitch");
this.playSound(Sound.of(key, source, volume, pitch));
}
}
} else if (sender.isOnline()) {
final String targetNameFinal = targetName;
final String senderNameFinal = senderName;
if (!carbonChat.isBungeeEnabled()) {
String playerOfflineFormat = carbonChat.getLanguage().getString("other-player-offline");
Component playerOfflineComponent = carbonChat.getAdventureManager().processMessage(playerOfflineFormat,
"br", "\n",
"message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName,
"target", targetNameFinal, "sender", senderNameFinal);
sender.sendMessage(playerOfflineComponent);
return;
}
BungeeChannelApi.of(carbonChat).getPlayerList("ALL").thenAccept(list -> {
if (!list.contains(this.asOfflinePlayer().getName())) {
String playerOfflineFormat = carbonChat.getLanguage().getString("other-player-offline");
Component playerOfflineComponent = carbonChat.getAdventureManager().processMessage(playerOfflineFormat,
"br", "\n",
"message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName,
"target", targetNameFinal, "sender", senderNameFinal);
sender.sendMessage(playerOfflineComponent);
return;
}
sender.sendMessage(toPlayerComponent);
carbonChat.getMessageManager().sendMessage("whisper-component", sender.getUUID(), (byteArray) -> {
byteArray.writeLong(this.getUUID().getMostSignificantBits());
byteArray.writeLong(this.getUUID().getLeastSignificantBits());
byteArray.writeUTF(carbonChat.getAdventureManager().getAudiences().gsonSerializer().serialize(fromPlayerComponent));
});
});
}
for (Player player : Bukkit.getOnlinePlayers()) {
ChatUser user = carbonChat.getUserService().wrap(player);
if (!user.isSpyingWhispers()) {
continue;
}
if (user.getUUID().equals(sender.getUUID()) || user.getUUID().equals(getUUID())) {
continue;
}
user.sendMessage(carbonChat.getAdventureManager().processMessage(carbonChat.getLanguage().getString("spy-whispers"),
"br", "\n", "message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName,
"target", targetName, "sender", senderName));
}
if (this.online()) {
targetName = this.player().getDisplayName();
}
final Component toPlayerComponent = this.carbonChat.adventureManager().processMessage(toPlayerFormat, "br", "\n",
"message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName,
"target", targetName, "sender", senderName);
final Component fromPlayerComponent = this.carbonChat.adventureManager().processMessage(fromPlayerFormat, "br", "\n",
"message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName,
"target", targetName, "sender", senderName);
final PrivateMessageEvent event = new PrivateMessageEvent(sender, this, toPlayerComponent, fromPlayerComponent, message);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled()) {
return;
}
if (this.online()) {
if (sender.online()) {
sender.sendMessage(toPlayerComponent);
if (sender.shadowMuted()) {
return;
}
this.sendMessage(fromPlayerComponent);
sender.replyTarget(this);
this.replyTarget(sender);
if (this.carbonChat.getConfig().getBoolean("pings.on-whisper")) {
final Key key = Key.of(this.carbonChat.getConfig().getString("pings.sound"));
final Sound.Source source = Sound.Source.valueOf(this.carbonChat.getConfig().getString("pings.source"));
final float volume = (float) this.carbonChat.getConfig().getDouble("pings.volume");
final float pitch = (float) this.carbonChat.getConfig().getDouble("pings.pitch");
this.playSound(Sound.of(key, source, volume, pitch));
}
}
} else if (sender.online()) {
final String targetNameFinal = targetName;
final String senderNameFinal = senderName;
if (!this.carbonChat.bungeeEnabled()) {
final String playerOfflineFormat = this.carbonChat.language().getString("other-player-offline");
final Component playerOfflineComponent = this.carbonChat.adventureManager().processMessage(playerOfflineFormat,
"br", "\n",
"message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName,
"target", targetNameFinal, "sender", senderNameFinal);
sender.sendMessage(playerOfflineComponent);
return;
}
BungeeChannelApi.of(this.carbonChat).getPlayerList("ALL").thenAccept(list -> {
if (!list.contains(this.offlinePlayer().getName())) {
final String playerOfflineFormat = this.carbonChat.language().getString("other-player-offline");
final Component playerOfflineComponent = this.carbonChat.adventureManager().processMessage(playerOfflineFormat,
"br", "\n",
"message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName,
"target", targetNameFinal, "sender", senderNameFinal);
sender.sendMessage(playerOfflineComponent);
return;
}
sender.sendMessage(toPlayerComponent);
this.carbonChat.messageManager().sendMessage("whisper-component", sender.uuid(), byteArray -> {
byteArray.writeLong(this.uuid().getMostSignificantBits());
byteArray.writeLong(this.uuid().getLeastSignificantBits());
byteArray.writeUTF(this.carbonChat.adventureManager().audiences().gsonSerializer().serialize(fromPlayerComponent));
});
});
}
for (final Player player : Bukkit.getOnlinePlayers()) {
final ChatUser user = this.carbonChat.userService().wrap(player);
if (!user.spyingwhispers()) {
continue;
}
if (user.uuid().equals(sender.uuid()) || user.uuid().equals(this.uuid())) {
continue;
}
user.sendMessage(this.carbonChat.adventureManager().processMessage(this.carbonChat.language().getString("spy-whispers"),
"br", "\n", "message", message,
"targetname", targetOfflineName, "sendername", senderOfflineName,
"target", targetName, "sender", senderName));
}
}
}
@@ -28,123 +28,123 @@ import java.util.concurrent.ExecutionException;
public class JSONUserService implements UserService {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
@NonNull
private final Type userType = new TypeToken<CarbonChatUser>() {}.getType();
@NonNull
private final LoadingCache<@NonNull UUID, @NonNull CarbonChatUser> userCache = CacheBuilder.newBuilder()
.removalListener(this::saveUser)
.build(CacheLoader.from(this::loadUser));
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final Gson gson = new GsonBuilder().setPrettyPrinting().create();
@NonNull
private final Type userType = new TypeToken<CarbonChatUser>() {}.getType();
@NonNull
private final LoadingCache<@NonNull UUID, @NonNull CarbonChatUser> userCache = CacheBuilder.newBuilder()
.removalListener(this::saveUser)
.build(CacheLoader.from(this::loadUser));
public JSONUserService(@NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
public JSONUserService(@NonNull final 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
public void onDisable() {
this.userCache.invalidateAll();
this.userCache.cleanUp();
}
@Override
@Nullable
public ChatUser wrap(@NonNull final String name) {
final Player player = Bukkit.getPlayer(name);
if (player != null) {
return this.wrap(player);
}
@Override
public void onDisable() {
userCache.invalidateAll();
userCache.cleanUp();
return this.wrap(Bukkit.getOfflinePlayer(name));
}
@Override
@Nullable
public ChatUser wrap(@NonNull final OfflinePlayer player) {
return this.wrap(player.getUniqueId());
}
@Override
@Nullable
public ChatUser wrap(@NonNull final UUID uuid) {
try {
return this.userCache.get(uuid);
} catch (final ExecutionException exception) {
exception.printStackTrace();
return null;
}
}
@Override
@Nullable
public ChatUser wrapIfLoaded(@NonNull final UUID uuid) {
return this.userCache.getIfPresent(uuid);
}
@Override
@Nullable
public ChatUser refreshUser(@NonNull final UUID uuid) {
this.userCache.invalidate(uuid);
return this.wrap(uuid);
}
@Override
public void invalidate(@NonNull final ChatUser user) {
this.userCache.invalidate(user.uuid());
}
@Override
public void validate(@NonNull final ChatUser user) {
this.userCache.put(user.uuid(), (CarbonChatUser) user);
}
@NonNull
private CarbonChatUser loadUser(@NonNull final UUID uuid) {
final File userFile = new File(this.carbonChat.getDataFolder(), "users/" + uuid.toString() + ".json");
this.ensureFileExists(userFile);
try (final JsonReader reader = this.gson.newJsonReader(new FileReader(userFile))) {
final CarbonChatUser user = this.gson.fromJson(reader, this.userType);
if (user != null) {
return user;
}
} catch (final IOException exception) {
exception.printStackTrace();
}
@Override
@Nullable
public ChatUser wrap(@NonNull String name) {
Player player = Bukkit.getPlayer(name);
return new CarbonChatUser(uuid);
}
if (player != null) {
return wrap(player);
}
private void saveUser(@NonNull final RemovalNotification<@NonNull UUID, @NonNull CarbonChatUser> notification) {
final File userFile = new File(this.carbonChat.getDataFolder(), "users/" + notification.getKey().toString() + ".json");
this.ensureFileExists(userFile);
return wrap(Bukkit.getOfflinePlayer(name));
try (final JsonWriter writer = this.gson.newJsonWriter(new FileWriter(userFile))) {
this.gson.toJson(notification.getValue(), this.userType, writer);
} catch (final IOException exception) {
exception.printStackTrace();
}
}
private void ensureFileExists(@NonNull final File file) {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
@Override
@Nullable
public ChatUser wrap(@NonNull OfflinePlayer player) {
return wrap(player.getUniqueId());
}
@Override
@Nullable
public ChatUser wrap(@NonNull UUID uuid) {
try {
return userCache.get(uuid);
} catch (ExecutionException e) {
e.printStackTrace();
return null;
}
}
@Override
@Nullable
public ChatUser wrapIfLoaded(@NonNull UUID uuid) {
return userCache.getIfPresent(uuid);
}
@Override
@Nullable
public ChatUser refreshUser(@NonNull UUID uuid) {
userCache.invalidate(uuid);
return this.wrap(uuid);
}
@Override
public void invalidate(@NonNull ChatUser user) {
userCache.invalidate(user.getUUID());
}
@Override
public void validate(@NonNull ChatUser user) {
userCache.put(user.getUUID(), (CarbonChatUser) user);
}
@NonNull
private CarbonChatUser loadUser(@NonNull UUID uuid) {
File userFile = new File(carbonChat.getDataFolder(), "users/" + uuid.toString() + ".json");
ensureFileExists(userFile);
try (JsonReader reader = gson.newJsonReader(new FileReader(userFile))) {
CarbonChatUser user = gson.fromJson(reader, userType);
if (user != null) {
return user;
}
} catch (IOException e) {
e.printStackTrace();
}
return new CarbonChatUser(uuid);
}
private void saveUser(@NonNull RemovalNotification<@NonNull UUID, @NonNull CarbonChatUser> notification) {
File userFile = new File(carbonChat.getDataFolder(), "users/" + notification.getKey().toString() + ".json");
ensureFileExists(userFile);
try (JsonWriter writer = gson.newJsonWriter(new FileWriter(userFile))) {
gson.toJson(notification.getValue(), userType, writer);
} catch (IOException e) {
e.printStackTrace();
}
}
private void ensureFileExists(@NonNull File file) {
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if (!file.exists()) {
try {
file.createNewFile();
} catch (final IOException exception) {
exception.printStackTrace();
}
}
}
}
@@ -1,6 +1,11 @@
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.CacheLoader;
import com.google.common.cache.LoadingCache;
@@ -27,218 +32,218 @@ import java.util.concurrent.ExecutionException;
public class MySQLUserService implements UserService {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final Database database;
@NonNull
private final LoadingCache<@NonNull UUID, @NonNull CarbonChatUser> userCache = CacheBuilder.newBuilder()
.removalListener(this::saveUser)
.build(CacheLoader.from(this::loadUser));
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final Database database;
@NonNull
private final LoadingCache<@NonNull UUID, @NonNull CarbonChatUser> userCache = CacheBuilder.newBuilder()
.removalListener(this::saveUser)
.build(CacheLoader.from(this::loadUser));
public MySQLUserService(@NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
public MySQLUserService(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat;
ConfigurationSection section = carbonChat.getConfig().getConfigurationSection("storage");
final ConfigurationSection section = this.carbonChat.getConfig().getConfigurationSection("storage");
if (section == null) {
throw new IllegalStateException("Missing Database Credentials!");
}
String username = section.getString("username", "username");
String password = section.getString("password", "password");
String dbname = section.getString("database", "0");
String hostandport = section.getString("hostname", "hostname") + ":" + section.getString("port", "0");
database = new HikariPooledDatabase(BukkitDB.getRecommendedOptions(carbonChat, username, password, dbname, hostandport));
DB.setGlobalDatabase(database);
try {
database.executeUpdate("CREATE TABLE IF NOT EXISTS sc_users (uuid CHAR(36) PRIMARY KEY," +
"channel VARCHAR(16), muted BOOLEAN, shadowmuted BOOLEAN, spyingwhispers BOOLEAN," +
"nickname VARCHAR(512))");
// Ignore the exception, it's just saying the column already exists
try {
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");
} catch (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))");
database.executeUpdate("CREATE TABLE IF NOT EXISTS sc_ignored_users (uuid CHAR(36), user CHAR(36), PRIMARY KEY (uuid, user))");
} catch (SQLException e) {
e.printStackTrace();
}
if (section == null) {
throw new IllegalStateException("Missing Database Credentials!");
}
@Override
public void onDisable() {
userCache.invalidateAll();
userCache.cleanUp();
database.close();
final String username = section.getString("username", "username");
final String password = section.getString("password", "password");
final String dbname = section.getString("database", "0");
final String hostandport = section.getString("hostname", "hostname") + ":" + section.getString("port", "0");
this.database = new HikariPooledDatabase(BukkitDB.getRecommendedOptions(carbonChat, username, password, dbname, hostandport));
DB.setGlobalDatabase(this.database);
try {
this.database.executeUpdate("CREATE TABLE IF NOT EXISTS sc_users (uuid CHAR(36) PRIMARY KEY," +
"channel VARCHAR(16), muted BOOLEAN, shadowmuted BOOLEAN, spyingwhispers BOOLEAN," +
"nickname VARCHAR(512))");
// Ignore the exception, it's just saying the column already exists
try {
this.database.executeUpdate("ALTER TABLE sc_users ADD COLUMN spyingwhispers BOOLEAN DEFAULT false");
this.database.executeUpdate("ALTER TABLE sc_users ADD COLUMN nickname VARCHAR(512) DEFAULT false");
} catch (final SQLSyntaxErrorException ignored) {
}
this.database.executeUpdate("CREATE TABLE IF NOT EXISTS sc_channel_settings (uuid CHAR(36), channel CHAR(16), spying BOOLEAN, ignored BOOLEAN, color TINYTEXT, PRIMARY KEY (uuid, channel))");
this.database.executeUpdate("CREATE TABLE IF NOT EXISTS sc_ignored_users (uuid CHAR(36), user CHAR(36), PRIMARY KEY (uuid, user))");
} catch (final SQLException exception) {
exception.printStackTrace();
}
}
@Override
public void onDisable() {
this.userCache.invalidateAll();
this.userCache.cleanUp();
this.database.close();
}
@Override
@Nullable
public ChatUser wrap(@NonNull final String name) {
final Player player = Bukkit.getPlayer(name);
if (player != null) {
return this.wrap(player);
}
@Override
@Nullable
public ChatUser wrap(@NonNull String name) {
Player player = Bukkit.getPlayer(name);
return this.wrap(Bukkit.getOfflinePlayer(name));
}
if (player != null) {
return wrap(player);
}
@Override
@Nullable
public ChatUser wrap(@NonNull final OfflinePlayer player) {
return this.wrap(player.getUniqueId());
}
return wrap(Bukkit.getOfflinePlayer(name));
@Override
@Nullable
public ChatUser wrap(@NonNull final UUID uuid) {
try {
return this.userCache.get(uuid);
} catch (final ExecutionException exception) {
exception.printStackTrace();
return null;
}
}
@Override
@Nullable
public ChatUser wrap(@NonNull OfflinePlayer player) {
return wrap(player.getUniqueId());
}
@Override
@Nullable
public ChatUser wrapIfLoaded(@NonNull final UUID uuid) {
return this.userCache.getIfPresent(uuid);
}
@Override
@Nullable
public ChatUser wrap(@NonNull UUID uuid) {
try {
return userCache.get(uuid);
} catch (ExecutionException e) {
e.printStackTrace();
return null;
}
}
@Override
@Nullable
public ChatUser refreshUser(@NonNull final UUID uuid) {
this.userCache.invalidate(uuid);
@Override
@Nullable
public ChatUser wrapIfLoaded(@NonNull UUID uuid) {
return userCache.getIfPresent(uuid);
}
return this.wrap(uuid);
}
@Override
@Nullable
public ChatUser refreshUser(@NonNull UUID uuid) {
userCache.invalidate(uuid);
@Override
public void invalidate(@NonNull final ChatUser user) {
this.userCache.invalidate(user.uuid());
}
return this.wrap(uuid);
}
@Override
public void validate(@NonNull final ChatUser user) {
this.userCache.put(user.uuid(), (CarbonChatUser) user);
}
@Override
public void invalidate(@NonNull ChatUser user) {
userCache.invalidate(user.getUUID());
}
@NonNull
private CarbonChatUser loadUser(@NonNull final UUID uuid) {
final CarbonChatUser user = new CarbonChatUser(uuid);
@Override
public void validate(@NonNull ChatUser user) {
userCache.put(user.getUUID(), (CarbonChatUser) user);
}
try (final DbStatement statement = this.database.query("SELECT * from sc_users WHERE uuid = ?;")) {
statement.execute(uuid.toString());
@NonNull
private CarbonChatUser loadUser(@NonNull UUID uuid) {
CarbonChatUser user = new CarbonChatUser(uuid);
try (DbStatement statement = database.query("SELECT * from sc_users WHERE uuid = ?;")) {
statement.execute(uuid.toString());
DbRow users = statement.getNextRow();
if (users == null) {
return user;
}
List<DbRow> channelSettings = 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());
ChatChannel channel = carbonChat.getChannelManager().getChannelOrDefault(users.getString("channel"));
if (channel != null) {
user.setSelectedChannel(channel, true);
}
String nickname = users.getString("nickname");
if (nickname != null) {
user.setNickname(nickname, true);
}
user.setMuted(users.<Boolean>get("muted"), true);
user.setShadowMuted(users.<Boolean>get("shadowmuted"), true);
user.setSpyingWhispers(users.<Boolean>get("spyingwhispers"), true);
for (DbRow channelSetting : channelSettings) {
ChatChannel chatChannel = carbonChat.getChannelManager().getRegistry().get(channelSetting.getString("channel"));
if (chatChannel != null) {
UserChannelSettings settings = user.getChannelSettings(chatChannel);
settings.setSpying(channelSetting.<Boolean>get("spying"), true);
settings.setIgnoring(channelSetting.<Boolean>get("ignored"), true);
String color = channelSetting.getString("color");
if (color != null) {
settings.setColor(TextColor.fromHexString(color), true);
}
}
}
for (DbRow ignoredUser : ignoredUsers) {
user.setIgnoringUser(UUID.fromString(ignoredUser.getString("user")), true, true);
}
} catch (SQLException e) {
e.printStackTrace();
}
final DbRow users = statement.getNextRow();
if (users == null) {
return user;
}
final List<DbRow> channelSettings = this.database.getResults("SELECT * from sc_channel_settings WHERE uuid = ?;", uuid.toString());
final List<DbRow> ignoredUsers = this.database.getResults("SELECT * from sc_ignored_users WHERE uuid = ?;", uuid.toString());
final ChatChannel channel = this.carbonChat.channelManager().channelOrDefault(users.getString("channel"));
if (channel != null) {
user.selectedChannel(channel, true);
}
final String nickname = users.getString("nickname");
if (nickname != null) {
user.nickname(nickname, true);
}
user.muted(users.<Boolean>get("muted"), true);
user.shadowMuted(users.<Boolean>get("shadowmuted"), true);
user.spyingWhispers(users.<Boolean>get("spyingwhispers"), true);
for (final DbRow channelSetting : channelSettings) {
final ChatChannel chatChannel = this.carbonChat.channelManager().registry().channel(channelSetting.getString("channel"));
if (chatChannel != null) {
final UserChannelSettings settings = user.channelSettings(chatChannel);
settings.spying(channelSetting.<Boolean>get("spying"), true);
settings.ignoring(channelSetting.<Boolean>get("ignored"), true);
final String color = channelSetting.getString("color");
if (color != null) {
settings.color(TextColor.fromHexString(color), true);
}
}
}
for (final DbRow ignoredUser : ignoredUsers) {
user.ignoringUser(UUID.fromString(ignoredUser.getString("user")), true, true);
}
} catch (final SQLException exception) {
exception.printStackTrace();
}
private void saveUser(@NonNull RemovalNotification<@NonNull UUID, @NonNull CarbonChatUser> notification) {
CarbonChatUser user = notification.getValue();
return user;
}
database.createTransaction(stm -> {
// Save user general data
String selectedName = null;
private void saveUser(@NonNull final RemovalNotification<@NonNull UUID, @NonNull CarbonChatUser> notification) {
final CarbonChatUser user = notification.getValue();
if (user.getSelectedChannel() != null) {
selectedName = user.getSelectedChannel().getKey();
}
this.database.createTransaction(stm -> {
// Save user general data
String selectedName = null;
carbonChat.getLogger().info("Saving user data!");
stm.executeUpdateQuery("INSERT INTO sc_users (uuid, channel, muted, shadowmuted, spyingwhispers, nickname) VALUES (?, ?, ?, ?, ?, ?) " +
"ON DUPLICATE KEY UPDATE channel = ?, muted = ?, shadowmuted = ?, spyingwhispers = ?, nickname =?",
user.getUUID().toString(), selectedName, user.isMuted(), user.isShadowMuted(), user.isSpyingWhispers(), user.getNickname(),
selectedName, user.isMuted(), user.isShadowMuted(), user.isSpyingWhispers(), user.getNickname());
if (user.selectedChannel() != null) {
selectedName = user.selectedChannel().key();
}
carbonChat.getLogger().info("Saving user channel settings!");
// Save user channel settings
for (Map.Entry<String, ? extends UserChannelSettings> entry : user.getChannelSettings().entrySet()) {
UserChannelSettings value = entry.getValue();
this.carbonChat.getLogger().info("Saving user data!");
stm.executeUpdateQuery("INSERT INTO sc_users (uuid, channel, muted, shadowmuted, spyingwhispers, nickname) VALUES (?, ?, ?, ?, ?, ?) " +
"ON DUPLICATE KEY UPDATE channel = ?, muted = ?, shadowmuted = ?, spyingwhispers = ?, nickname =?",
user.uuid().toString(), selectedName, user.muted(), user.shadowMuted(), user.spyingwhispers(), user.nickname(),
selectedName, user.muted(), user.shadowMuted(), user.spyingwhispers(), user.nickname());
String colorString = null;
this.carbonChat.getLogger().info("Saving user channel settings!");
// Save user channel settings
for (final Map.Entry<String, ? extends UserChannelSettings> entry : user.channelSettings().entrySet()) {
final UserChannelSettings value = entry.getValue();
if (value.getColor() != null) {
colorString = value.getColor().asHexString();
}
String colorString = null;
stm.executeUpdateQuery("INSERT INTO sc_channel_settings (uuid, channel, spying, ignored, color) VALUES (?, ?, ?, ?, ?) " +
"ON DUPLICATE KEY UPDATE spying = ?, ignored = ?, color = ?",
user.getUUID().toString(), entry.getKey(), value.isSpying(), value.isIgnored(), colorString,
value.isSpying(), value.isIgnored(), colorString);
}
if (value.color() != null) {
colorString = value.color().asHexString();
}
carbonChat.getLogger().info("Saving user ignores!");
// Save user ignore list (remove old entries then add new ones)
// TODO: keep DB up to date with settings as settings are mutated
stm.executeUpdateQuery("DELETE FROM sc_ignored_users WHERE uuid = ?", user.getUUID().toString());
stm.executeUpdateQuery("INSERT INTO sc_channel_settings (uuid, channel, spying, ignored, color) VALUES (?, ?, ?, ?, ?) " +
"ON DUPLICATE KEY UPDATE spying = ?, ignored = ?, color = ?",
user.uuid().toString(), entry.getKey(), value.spying(), value.ignored(), colorString,
value.spying(), value.ignored(), colorString);
}
for (UUID entry : user.getIgnoredUsers()) {
stm.executeUpdateQuery("INSERT INTO sc_ignored_users (uuid, user) VALUES (?, ?)",
user.getUUID().toString(), entry.toString());
}
this.carbonChat.getLogger().info("Saving user ignores!");
// Save user ignore list (remove old entries then add new ones)
// TODO: keep DB up to date with settings as settings are mutated
stm.executeUpdateQuery("DELETE FROM sc_ignored_users WHERE uuid = ?", user.uuid().toString());
return true;
});
}
for (final UUID entry : user.ignoredUsers()) {
stm.executeUpdateQuery("INSERT INTO sc_ignored_users (uuid, user) VALUES (?, ?)",
user.uuid().toString(), entry.toString());
}
return true;
});
}
}
@@ -12,90 +12,90 @@ import java.util.UUID;
public class SimpleUserChannelSettings implements UserChannelSettings {
@NonNull
private final transient CarbonChat carbonChat;
private boolean spying;
private boolean ignored;
@Nullable
private String color;
@MonotonicNonNull // @NonNull but not initialised in all constructors.
private UUID uuid;
@MonotonicNonNull // @NonNull but not initialised in all constructors.
private String channel;
@NonNull
private final transient CarbonChat carbonChat;
private boolean spying;
private boolean ignored;
@Nullable
private String color;
@MonotonicNonNull // @NonNull but not initialised in all constructors.
private UUID uuid;
@MonotonicNonNull // @NonNull but not initialised in all constructors.
private String channel;
private SimpleUserChannelSettings() {
carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
private SimpleUserChannelSettings() {
this.carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
}
public SimpleUserChannelSettings(@NonNull final UUID uuid, @NonNull final String channel) {
this.uuid = uuid;
this.channel = channel;
this.carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
}
@NonNull
private CarbonChatUser user() {
return (CarbonChatUser) this.carbonChat.userService().wrap(this.uuid);
}
@Override
public boolean spying() {
return this.spying;
}
@Override
public void spying(final boolean spying, final boolean fromRemote) {
this.spying = spying;
if (!fromRemote) {
this.carbonChat.messageManager().sendMessage("spying-channel", this.uuid, byteArray -> {
byteArray.writeUTF(this.channel);
byteArray.writeBoolean(spying);
});
}
}
@Override
public boolean ignored() {
return this.ignored;
}
@Override
public void ignoring(final boolean ignored, final boolean fromRemote) {
this.ignored = ignored;
if (!fromRemote) {
this.carbonChat.messageManager().sendMessage("ignoring-channel", this.uuid, byteArray -> {
byteArray.writeUTF(this.channel);
byteArray.writeBoolean(ignored);
});
}
}
@Override
@Nullable
public TextColor color() {
if (this.color == null) {
return null;
}
public SimpleUserChannelSettings(@NonNull UUID uuid, @NonNull String channel) {
this.uuid = uuid;
this.channel = channel;
return TextColor.fromHexString(this.color);
}
carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
@Override
public void color(@Nullable final TextColor color, final boolean fromRemote) {
if (color == null) {
this.color = null;
} else {
this.color = color.asHexString();
}
@NonNull
private CarbonChatUser getUser() {
return (CarbonChatUser) carbonChat.getUserService().wrap(uuid);
}
@Override
public boolean isSpying() {
return this.spying;
}
@Override
public void setSpying(boolean spying, boolean fromRemote) {
this.spying = spying;
if (!fromRemote) {
carbonChat.getMessageManager().sendMessage("spying-channel", uuid, (byteArray) -> {
byteArray.writeUTF(channel);
byteArray.writeBoolean(spying);
});
}
}
@Override
public boolean isIgnored() {
return ignored;
}
@Override
public void setIgnoring(boolean ignored, boolean fromRemote) {
this.ignored = ignored;
if (!fromRemote) {
carbonChat.getMessageManager().sendMessage("ignoring-channel", uuid, (byteArray) -> {
byteArray.writeUTF(channel);
byteArray.writeBoolean(ignored);
});
}
}
@Override
@Nullable
public TextColor getColor() {
if (color == null) {
return null;
}
return TextColor.fromHexString(color);
}
@Override
public void setColor(@Nullable TextColor color, boolean fromRemote) {
if (color == null) {
this.color = null;
} else {
this.color = color.asHexString();
}
if (!fromRemote) {
carbonChat.getMessageManager().sendMessage("channel-color", uuid, (byteArray) -> {
byteArray.writeUTF(color.asHexString());
});
}
if (!fromRemote) {
this.carbonChat.messageManager().sendMessage("channel-color", this.uuid, byteArray -> {
byteArray.writeUTF(color.asHexString());
});
}
}
}
@@ -10,84 +10,84 @@ import org.checkerframework.checker.nullness.qual.Nullable;
public class CarbonPlaceholders extends PlaceholderExpansion {
@NonNull
private final CarbonChat carbonChat;
@NonNull
private final CarbonChat carbonChat;
public CarbonPlaceholders(@NonNull CarbonChat carbonChat) {
this.carbonChat = carbonChat;
public CarbonPlaceholders(@NonNull final CarbonChat carbonChat) {
this.carbonChat = carbonChat;
}
@Override
@NonNull
public String getIdentifier() {
return "carbonchat";
}
@Override
@NonNull
public String getAuthor() {
return "Draycia (Vicarious#0001)";
}
@Override
@NonNull
public String getVersion() {
return "1.0.0";
}
@Override
public boolean persist() {
return true;
}
@Override
@Nullable
public String onPlaceholderRequest(@NonNull final Player player, @NonNull final String identifier) {
final String key = identifier.toLowerCase();
if (key.startsWith("can_use_")) {
final String value = key.replace("can_use_", "");
final ChatChannel channel = this.carbonChat.channelManager().registry().channel(value);
if (channel == null) {
return "false";
}
final ChatUser user = this.carbonChat.userService().wrap(player);
return String.valueOf(channel.canPlayerUse(user));
} else if (key.startsWith("can_see_")) {
final String value = key.replace("can_see_", "");
final ChatChannel channel = this.carbonChat.channelManager().registry().channel(value);
if (channel == null) {
return "false";
}
final ChatUser user = this.carbonChat.userService().wrap(player);
return String.valueOf(channel.canPlayerSee(user, true));
} else if (key.startsWith("ignoring_channel_")) {
final String value = key.replace("ignoring_channel_", "");
final ChatChannel channel = this.carbonChat.channelManager().registry().channel(value);
if (channel == null) {
return "false";
}
final ChatUser user = this.carbonChat.userService().wrap(player);
return String.valueOf(user.channelSettings(channel).ignored());
} else if (key.startsWith("selected_channel")) {
final ChatChannel channel = this.carbonChat.userService().wrap(player).selectedChannel();
return channel == null ? this.carbonChat.channelManager().defaultChannel().name() : channel.name();
}
@Override
@NonNull
public String getIdentifier() {
return "carbonchat";
}
@Override
@NonNull
public String getAuthor() {
return "Draycia (Vicarious#0001)";
}
@Override
@NonNull
public String getVersion() {
return "1.0.0";
}
@Override
public boolean persist() {
return true;
}
@Override
@Nullable
public String onPlaceholderRequest(@NonNull final Player player, @NonNull final String identifier) {
String key = identifier.toLowerCase();
if (key.startsWith("can_use_")) {
String value = key.replace("can_use_", "");
ChatChannel channel = carbonChat.getChannelManager().getRegistry().get(value);
if (channel == null) {
return "false";
}
ChatUser user = carbonChat.getUserService().wrap(player);
return String.valueOf(channel.canPlayerUse(user));
} else if (key.startsWith("can_see_")) {
String value = key.replace("can_see_", "");
ChatChannel channel = carbonChat.getChannelManager().getRegistry().get(value);
if (channel == null) {
return "false";
}
ChatUser user = carbonChat.getUserService().wrap(player);
return String.valueOf(channel.canPlayerSee(user, true));
} else if (key.startsWith("ignoring_channel_")) {
String value = key.replace("ignoring_channel_", "");
ChatChannel channel = carbonChat.getChannelManager().getRegistry().get(value);
if (channel == null) {
return "false";
}
ChatUser user = carbonChat.getUserService().wrap(player);
return String.valueOf(user.getChannelSettings(channel).isIgnored());
} else if (key.startsWith("selected_channel")) {
ChatChannel channel = carbonChat.getUserService().wrap(player).getSelectedChannel();
return channel == null ? carbonChat.getChannelManager().getDefaultChannel().getName() : channel.getName();
}
return null;
}
return null;
}
}
@@ -49,162 +49,166 @@ import java.util.List;
public final class CarbonUtils {
private static final @NonNull String @NonNull [] colors;
private static final @NonNull String @NonNull [] colors;
static {
List<String> colorList = new ArrayList<>();
private CarbonUtils() {
for (NamedTextColor color : NamedTextColor.values()) {
colorList.add(color.toString());
}
}
colors = colorList.toArray(new String[0]);
static {
final List<String> colorList = new ArrayList<>();
for (final NamedTextColor color : NamedTextColor.values()) {
colorList.add(color.toString());
}
@NonNull
public static Component createComponent(@NonNull final Player player) {
if (!FunctionalityConstants.HAS_HOVER_EVENT_METHOD) {
return net.kyori.adventure.text.TextComponent.empty();
}
colors = colorList.toArray(new String[0]);
}
final ItemStack itemStack = player.getInventory().getItemInMainHand();
if (itemStack.getType().isAir()) {
return net.kyori.adventure.text.TextComponent.empty();
}
Content content = Bukkit.getItemFactory().hoverContentOf(itemStack);
HoverEvent event = new HoverEvent(HoverEvent.Action.SHOW_ITEM, content);
ComponentBuilder component = new ComponentBuilder();
component.event(event); // Let this be inherited by all coming components.
component.color(ChatColor.WHITE).append("[");
if (itemStack.getItemMeta().hasDisplayName()) {
component.append(TextComponent.fromLegacyText(itemStack.getItemMeta().getDisplayName()));
} else {
String name = itemStack.getItemMeta().hasDisplayName()
? itemStack.getItemMeta().getDisplayName()
: "item.minecraft." + itemStack.getType().name().toLowerCase(); // As of 1.13, Material is 1:1 with MC's names
component.append(new TranslatableComponent(name));
}
component.color(ChatColor.WHITE).append("]");
return BungeeCordComponentSerializer.get().deserialize(component.create());
@NonNull
public static Component createComponent(@NonNull final Player player) {
if (!FunctionalityConstants.HAS_HOVER_EVENT_METHOD) {
return net.kyori.adventure.text.TextComponent.empty();
}
@Nullable
public static TextColor parseColor(@Nullable String input) {
return parseColor(null, input);
final ItemStack itemStack = player.getInventory().getItemInMainHand();
if (itemStack.getType().isAir()) {
return net.kyori.adventure.text.TextComponent.empty();
}
@Nullable
public static TextColor parseColor(@Nullable ChatUser user, @Nullable String input) {
if (input == null) {
input = "white";
}
final Content content = Bukkit.getItemFactory().hoverContentOf(itemStack);
final HoverEvent event = new HoverEvent(HoverEvent.Action.SHOW_ITEM, content);
if (user != null && user.isOnline()) {
input = PlaceholderAPI.setPlaceholders(user.asPlayer(), input);
}
final ComponentBuilder component = new ComponentBuilder();
component.event(event); // Let this be inherited by all coming components.
component.color(ChatColor.WHITE).append("[");
for (NamedTextColor namedColor : NamedTextColor.values()) {
if (namedColor.toString().equalsIgnoreCase(input)) {
return namedColor;
}
}
if (input.contains("&") || input.contains("§")) {
input = input.replace("&", "§");
return LegacyComponentSerializer.legacySection().deserialize(input).color();
}
return TextColor.fromCSSHexString(input);
if (itemStack.getItemMeta().hasDisplayName()) {
component.append(TextComponent.fromLegacyText(itemStack.getItemMeta().getDisplayName()));
} else {
final String name = itemStack.getItemMeta().hasDisplayName()
? itemStack.getItemMeta().getDisplayName()
: "item.minecraft." + itemStack.getType().name().toLowerCase(); // As of 1.13, Material is 1:1 with MC's names
component.append(new TranslatableComponent(name));
}
@NonNull
public static Argument onlineChatUserArgument() {
return new CustomArgument<>((input) -> {
CarbonChat carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
component.color(ChatColor.WHITE).append("]");
Player player = Bukkit.getPlayer(input);
return BungeeCordComponentSerializer.get().deserialize(component.create());
}
if (player == null) {
throw new CustomArgument.CustomArgumentException("Invalid player for input (" + input + ")");
}
@Nullable
public static TextColor parseColor(@Nullable final String input) {
return parseColor(null, input);
}
return carbonChat.getUserService().wrap(player);
// }).overrideSuggestions((sender, args) -> {
// ArrayList<String> players = new ArrayList<>();
//
// for (Player player : Bukkit.getOnlinePlayers()) {
// players.add(player.getName());
// }
//
// return players.toArray(new String[0]);
});
@Nullable
public static TextColor parseColor(@Nullable final ChatUser user, @Nullable String input) {
if (input == null) {
input = "white";
}
@NonNull
public static Argument chatUserArgument() {
return new CustomArgument<>((input) -> {
CarbonChat carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
return carbonChat.getUserService().wrap(input);
// }).overrideSuggestions((sender, args) -> {
// ArrayList<String> players = new ArrayList<>();
//
// for (Player player : Bukkit.getOnlinePlayers()) {
// players.add(player.getName());
// }
//
// return players.toArray(new String[0]);
});
if (user != null && user.online()) {
input = PlaceholderAPI.setPlaceholders(user.player(), input);
}
@NonNull
public static Argument textColorArgument() {
return new CustomArgument<>((input) -> {
TextColor color = parseColor(input);
if (color == null) {
throw new CustomArgument.CustomArgumentException("Invalid color for input (" + input + ")");
}
return color;
}).overrideSuggestions(colors);
for (final NamedTextColor namedColor : NamedTextColor.values()) {
if (namedColor.toString().equalsIgnoreCase(input)) {
return namedColor;
}
}
@NonNull
public static Argument channelArgument() {
return new CustomArgument<>((input) -> {
CarbonChat carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
if (input.contains("&") || input.contains("§")) {
input = input.replace("&", "§");
ChatChannel channel = carbonChat.getChannelManager().getRegistry().get(input);
if (channel == null) {
throw new CustomArgument.CustomArgumentException("Invalid channel for input (" + input + ")");
}
return channel;
// }).overrideSuggestions((sender, args) -> {
// CarbonChat carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
//
// ArrayList<String> channels = new ArrayList<>();
//
// for (ChatChannel channel : carbonChat.getChannelManager().getRegistry().values()) {
// channels.add(channel.getKey());
// }
//
// return channels.toArray(new String[0]);
});
return LegacyComponentSerializer.legacySection().deserialize(input).color();
}
@NonNull
public static Argument usableChannelArgument() {
throw new NotImplementedException("Not implemented yet.");
}
return TextColor.fromCSSHexString(input);
}
}
@NonNull
public static Argument onlineChatUserArgument() {
return new CustomArgument<>(input -> {
final CarbonChat carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
final Player player = Bukkit.getPlayer(input);
if (player == null) {
throw new CustomArgument.CustomArgumentException("Invalid player for input (" + input + ")");
}
return carbonChat.userService().wrap(player);
// }).overrideSuggestions((sender, args) -> {
// ArrayList<String> players = new ArrayList<>();
//
// for (Player player : Bukkit.getOnlinePlayers()) {
// players.add(player.getName());
// }
//
// return players.toArray(new String[0]);
});
}
@NonNull
public static Argument chatUserArgument() {
return new CustomArgument<>(input -> {
final CarbonChat carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
return carbonChat.userService().wrap(input);
// }).overrideSuggestions((sender, args) -> {
// ArrayList<String> players = new ArrayList<>();
//
// for (Player player : Bukkit.getOnlinePlayers()) {
// players.add(player.getName());
// }
//
// return players.toArray(new String[0]);
});
}
@NonNull
public static Argument textColorArgument() {
return new CustomArgument<>(input -> {
final TextColor color = parseColor(input);
if (color == null) {
throw new CustomArgument.CustomArgumentException("Invalid color for input (" + input + ")");
}
return color;
}).overrideSuggestions(colors);
}
@NonNull
public static Argument channelArgument() {
return new CustomArgument<>(input -> {
final CarbonChat carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
final ChatChannel channel = carbonChat.channelManager().registry().channel(input);
if (channel == null) {
throw new CustomArgument.CustomArgumentException("Invalid channel for input (" + input + ")");
}
return channel;
// }).overrideSuggestions((sender, args) -> {
// CarbonChat carbonChat = (CarbonChat) Bukkit.getPluginManager().getPlugin("CarbonChat");
//
// ArrayList<String> channels = new ArrayList<>();
//
// for (ChatChannel channel : this.carbonChat.getChannelManager().getRegistry().values()) {
// channels.add(channel.getKey());
// }
//
// return channels.toArray(new String[0]);
});
}
@NonNull
public static Argument usableChannelArgument() {
throw new NotImplementedException("Not implemented yet.");
}
}
@@ -4,14 +4,18 @@ import dev.jorel.commandapi.CommandAPI;
import net.draycia.carbon.storage.CommandSettings;
import org.checkerframework.checker.nullness.qual.NonNull;
public class CommandUtils {
public final class CommandUtils {
public static void handleDuplicateCommands(@NonNull CommandSettings settings) {
CommandAPI.unregister(settings.getName());
private CommandUtils() {
for (String command : settings.getAliases()) {
CommandAPI.unregister(command);
}
}
public static void handleDuplicateCommands(@NonNull final CommandSettings settings) {
CommandAPI.unregister(settings.name());
for (final String command : settings.aliases()) {
CommandAPI.unregister(command);
}
}
}
@@ -7,19 +7,23 @@ import org.checkerframework.checker.nullness.qual.NonNull;
@SuppressWarnings("ResultOfMethodCallIgnored") // This is a common pattern in this class.
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) {
try {
runnable.run();
return true;
} catch (Exception ex) {
return false;
}
}
private FunctionalityConstants() {
@FunctionalInterface
private interface ThrowingRunnable {
void run() throws Exception;
}
private static boolean noThrow(@NonNull final ThrowingRunnable runnable) {
try {
runnable.run();
return true;
} catch (final Exception ex) {
return false;
}
}
@FunctionalInterface
private interface ThrowingRunnable {
void run() throws Exception;
}
}
File diff suppressed because it is too large. Load diff
@@ -6,22 +6,27 @@ import org.checkerframework.checker.nullness.qual.NonNull;
@FunctionalInterface
public interface RedisListener extends RedisPubSubListener<String, String> {
@Override
void message(@NonNull String channel, @NonNull String message);
@Override
void message(@NonNull String channel, @NonNull String message);
@Override
default void message(@NonNull String pattern, @NonNull String channel, @NonNull String message) { }
@Override
default void message(@NonNull final String pattern, @NonNull final String channel, @NonNull final String message) {
}
@Override
default void subscribed(@NonNull String channel, long count) { }
@Override
default void subscribed(@NonNull final String channel, final long count) {
}
@Override
default void psubscribed(@NonNull String pattern, long count) { }
@Override
default void psubscribed(@NonNull final String pattern, final long count) {
}
@Override
default void unsubscribed(@NonNull String channel, long count) { }
@Override
default void unsubscribed(@NonNull final String channel, final long count) {
}
@Override
default void punsubscribed(@NonNull String pattern, long count) { }
@Override
default void punsubscribed(@NonNull final String pattern, final long count) {
}
}
@@ -7,35 +7,35 @@ import java.util.Collection;
public interface Registry<@NonNull T> {
/**
* Adds the specified key and value to the registry
*
* @param key The entry's key
* @param value The value to insert
* @return If successfully registered
*/
boolean register(@NonNull String key, @NonNull T value);
/**
* Adds the specified key and value to the registry
*
* @param key The entry's key
* @param value The value to insert
* @return If successfully registered
*/
boolean register(@NonNull String key, @NonNull T value);
/**
* Gets the list of registered values
*
* @return The list of registered values
*/
@NonNull
Collection<@NonNull T> values();
/**
* Gets the list of registered values
*
* @return The list of registered values
*/
@NonNull
Collection<@NonNull T> values();
/**
* Obtains an entry associated with the specified key
*
* @param key The key for the entry
* @return The entry associated with the key or {@code null} if unassociated
*/
@Nullable
T get(@NonNull String key);
/**
* Obtains an entry associated with the specified key
*
* @param key The key for the entry
* @return The entry associated with the key or {@code null} if unassociated
*/
@Nullable
T channel(@NonNull String key);
/**
* Clears all registered entries from the registry
*/
void clearAll();
/**
* Clears all registered entries from the registry
*/
void clearAll();
}